Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python handling multiple exceptions

I want to handle a specific exception in a certain way, and generically log 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 MyCustomException will be logged because it inherits from Exception. What can I do to avoid that?

like image 566
yayu Avatar asked Nov 05 '14 14:11

yayu


1 Answers

What else is going on in your code?

MyCustomException should be checked and handled before flow ever gets to 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
like image 108
dm03514 Avatar answered Oct 05 '22 19:10

dm03514