Python handles a few exceptions

I want to handle a specific exception in a certain way and generally write all the others. This is what I have:

class MyCustomException(Exception): pass try: something() except MyCustomException: something_custom() except Exception as e: #all others logging.error("{}".format(e)) 

The problem is that even a MyCustomException will be logged because it inherits from Exception . What can I do to avoid this?

+7
python exception-handling
source share
2 answers

What else is going on in your code?

MyCustomException must be checked and handled before the thread ever gets into the second except clause

 In [1]: def test(): ...: try: ...: raise ValueError() ...: except ValueError: ...: print('valueerror') ...: except Exception: ...: print('exception') ...: In [2]: test() valueerror In [3]: issubclass(ValueError,Exception) Out[3]: True 
+6
source share

Only the first matching exception block is executed:

 class X(Exception): pass try: raise X except X: print 1 except Exception: print 2 

prints only 1.

Even if you throw an exception in the exclusive block, it will not be caught by anyone other than the blocks:

 class X(Exception): pass try: raise X except X: print 1 0/0 except Exception: print 2 

prints 1 and raises ZeroDivisionError: integer division or modulo by zero

+6
source share

All Articles