Last active
May 12, 2019 18:13
-
-
Save DanielTakeshi/2a5423ded016f06b9aeb063185d2f97b to your computer and use it in GitHub Desktop.
Exception Testing in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Some exception testing. | |
The code in the `try` block will stop as soon as any exception is encountered. | |
https://realpython.com/python-exceptions/ | |
https://realpython.com/the-most-diabolical-python-antipattern/ | |
""" | |
a = 5 | |
# This is bad, will not print the actual exception error message. | |
try: | |
b = a / 0.0 | |
except: | |
print('BAD, no exception listed! oops, divide by zero\n') | |
# If you run this, you get an error because this is NOT a ValueError. | |
# That's why I am commenting this out --- it terminates the program. | |
#try: | |
# b = a / 0.0 | |
#except ValueError: | |
# print('ValueError. oops, divide by zero') | |
# Fortunately, this will work. | |
try: | |
b = a / 0.0 | |
except ZeroDivisionError: | |
print('ZeroDivisionError. oops, divide by zero') | |
print('And the program will proceed from here\n') | |
# And this is probably better because we actually print the `e`. | |
try: | |
b = a / 0.0 | |
except ZeroDivisionError as e: | |
print('ZeroDivisionError. oops, divide by zero. Here is the exception object:') | |
print(e) | |
print("") | |
# Actually, might as well do python logging (easiest that way). | |
# The 'caught an error' text will appear within the logger message. | |
# This error will go and print the stack trace as well. | |
import logging | |
try: | |
b = a / 0.0 | |
except ZeroDivisionError as e: | |
logging.exception('caught an error') | |
print('and code logic can still proceed from here\n\n') | |
import numpy as np | |
import scipy | |
from scipy.spatial import ConvexHull | |
points = np.array([ [0,0], [1,0], [2,0] ]) | |
try: | |
hull = ConvexHull(points) | |
except scipy.spatial.qhull.QhullError as e: | |
logging.exception(e) | |
print('\nwell, we caught an error ... lets proceed from here') | |
points = np.array([ [0,0], [1,0], [2,0], [3,0], [4,0]]) | |
try: | |
hull = ConvexHull(points) | |
except scipy.spatial.qhull.QhullError as e: | |
logging.exception(e) | |
print('\nwell, we caught an error ... lets proceed from here') | |
points = np.array([ [0,0], [1,0], [2,0], [3,0], [4,1]]) | |
try: | |
hull = ConvexHull(points) | |
print('\nvolume: {}'.format(hull.volume)) | |
except scipy.spatial.qhull.QhullError as e: | |
logging.exception(e) | |
print('\nshould work ...') |
Author
DanielTakeshi
commented
May 12, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment