Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a multiple inherited Exception does not catch the parent exception?

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)
like image 310
comalex3 Avatar asked Oct 25 '25 00:10

comalex3


2 Answers

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)
like image 54
alani Avatar answered Oct 26 '25 18:10

alani


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)
like image 40
Artyer Avatar answered Oct 26 '25 17:10

Artyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!