7

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?

1
  • How are you raising inside the something()? If it's raising a MyCustomException this code works properly. Commented Nov 5, 2014 at 14:41

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

6

Only the first matching except block will be executed:

class X(Exception): pass

try:
    raise X
except X:
    print 1
except Exception:
    print 2

only prints 1.

Even if you raise an exception in an except block, it won't be caught by the other except 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.