I'm assuming that following code suppose to print ("CustomExceptionALL"), but that never happens if we raise CustomException1, CustomException2 or CustomException3 while CustomExceptionALL works. Why except CustomExceptionALL doesn't catch CustomException3?
class CustomException1(Exception):
pass
class CustomException2(Exception):
pass
class CustomException3(Exception):
pass
class CustomExceptionALL(CustomException1, CustomException2, CustomException3):
pass
try:
raise CustomException3
except CustomExceptionALL as e:
print("CustomExceptionALL")
except Exception as e:
print(e)
The use case is more the other way round: you raise the derived exception and then catch it using the parent class. For example:
class Brexit(Exception):
pass
class Covid(Exception):
pass
class DoubleWhammy(Brexit, Covid):
pass
try:
raise DoubleWhammy
except Brexit as e:
print("Brexit")
except Exception as e:
print(e)
Because you can only catch subclasses of the specified exception. In your case, these two are false:
isinstance(CustomException3(), CustomExceptionALL) # False
issubclass(CustomException3, CustomExceptionALL) # False
(Because you are trying to catch a CustomExceptionALL, but a CustomException3 is not a CustomExceptionALL, but the other way around)
You can instead use a tuple of classes:
CustomExceptionALL = (CustomException1, CustomException2, CustomException3)
isinstance(CustomException3(), CustomExceptionALL) # True
issubclass(CustomException3, CustomExceptionALL) # True
try:
raise CustomException3
except CustomExceptionALL as e:
print("CustomExceptionALL") # This prints
except Exception as e:
print(e)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With