Exception handling tutorial¶
Imports¶
In [1]:
Copied!
from sys import path
from os.path import abspath
# Tell python to search for the files and modules starting from the working directory
module_path = abspath("..")
if module_path not in path:
path.append(module_path)
from sys import path
from os.path import abspath
# Tell python to search for the files and modules starting from the working directory
module_path = abspath("..")
if module_path not in path:
path.append(module_path)
Note: If we don't want to be telling Python where to search for our library, we can install it (in editable mode) in our conda environment using
pip install -e .
In [2]:
Copied!
from mypackage import Vector
from mypackage import Vector
Custom exceptions¶
Exception errors occur whenever syntactically correct Python code results in an error. In our Vector
class, we raised an error whenever the norm of the initialized vector was greater than the module constant MAX_NORM
. This custom error class, NormError
, was defined as a subclass of the built-in exception class ValueError
.
In [3]:
Copied!
vector = Vector(100, 200)
vector = Vector(100, 200)
--------------------------------------------------------------------------- NormError Traceback (most recent call last) Cell In[3], line 1 ----> 1 vector = Vector(100, 200) File ~/Documents/Code projects/Python-tips-tools/mypackage/vector/vector.py:70, in Vector.__init__(self, x, y) 67 self.y: float = y 69 if self.norm > MAX_NORM: ---> 70 raise NormError(self.norm) NormError: Norm = 223.60679774997897, but it cannot be greater than 100.
Exception handling¶
Custom exceptions come in handy when handling errors. For example, we can create a vector given two components and, in case the norm is too big, handle the NormError
to create a new "renormalized" vector
In [5]:
Copied!
from mypackage import NormError
x = 100
y = 200
try:
vector = Vector(x, y)
print(f"{vector = !s}")
except NormError:
print("Norm is too big, resizing the vector...")
x = x % 71
y = y % 71
vector = Vector(x, y)
print(f"{vector = !s}")
finally:
print("\nThe try-except statement ended!")
from mypackage import NormError
x = 100
y = 200
try:
vector = Vector(x, y)
print(f"{vector = !s}")
except NormError:
print("Norm is too big, resizing the vector...")
x = x % 71
y = y % 71
vector = Vector(x, y)
print(f"{vector = !s}")
finally:
print("\nThe try-except statement ended!")
Norm is too big, resizing the vector... vector = (29, 58) The try-except statement ended!