How to raise an exception in one except block and catch it in a later except block in Python?



Only a single except clause in a try block is invoked. If you want the exception to be caught higher up then you will need to use nested try blocks.

Let us write 2 try...except blocks like this:

try: try: 1/0 except ArithmeticError as e: if str(e) == "Zero division": print ("thumbs up") else: raise except Exception as err: print ("thumbs down") raise err

we get the following output

thumbs down Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~.py", line 11, in <module> raise err File "C:/Users/TutorialsPoint1/~.py", line 3, in <module> 1/0 ZeroDivisionError: division by zero

As per python tutorial there is one and only one caught or catched exception per one try statement.

Updated on: 2019-09-27T11:27:53+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements