I am trying to understand how to use custom exceptions in Python using the try-except construction.
Here is a simple example of a custom exception:
# create custom error class
class CustomError1(Exception):
pass
I attempted to use it like so:
# using try-except
def fnFoo1(tuple1, tuple2):
try:
assert(len(tuple1) == len(tuple2))
except AssertionError:
raise(CustomError1)
return(1)
fnFoo1((1,2), (1, 2, 3))
This raises the CustomeError1 but also raises the AssertionError, which I would like to subsume in CustomError1.
The following does what I want, but does not seem to be the way that exceptions should be handled.
# use the custom error function without try-catch
def fnFoo2(tuple1, tuple2):
if len(tuple1) != len(tuple2): raise(CustomError1)
print('All done!')
fnFoo2((1,2), (1, 2, 3))
What is the way to write custom exceptions that hide other exceptions?