N Randhawa
N Randhawa

Reputation: 9511

How to handle exception chaining raised from the except block

In my example I have a custom exception class MyCustomException and in main I divide an integer a by zero which raises a ZeroDivisionError exception. With the except block I catch ZeroDivisionError and then raise MyCustomException from err; this creates a chained exception, my own, plus the one in err.

Now how can I catch chained exceptions or how do chained exceptions work? Python doen't let me to catch MyCustomException in my code with except block.

class MyCustomException(Exception):
    pass

a=10
b=0 
reuslt=None

try:
    result=a/b

except ZeroDivisionError as err:
    print("ZeroDivisionError -- ",err)
    raise MyCustomException from err

except MyCustomException as e:
        print("MyException",e)                 # unable to catch MyCustomException

The output I get when I execute it:

ZeroDivisionError --  division by zero
Traceback (most recent call last):
  File "python", line 13, in <module>
MyCustomException

Upvotes: 1

Views: 1817

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160397

Using raise in the except clause won't search for exception handlers in the same try block (it did not occur in that try block).

It will search for handlers one level up , that is, an outer try block. If that isn't found it'll interrupt execution as it normally does (resulting in the exception being displayed).

In short, you need an enclosing try in the outer level with the appropriate except MyCustomException in order to catch your custom exception:

try:
    try:
        result=a/b
    except ZeroDivisionError as err:
        print("ZeroDivisionError -- ",err)
        raise MyCustomException from err

except MyCustomException as e:
    print("Caught MyException", e)

Which, when executed, now prints out:

ZeroDivisionError --  division by zero
Caught MyException 

Upvotes: 3

Related Questions