Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I would like to know if it is possible in python to raise an exception in one except block and catch it in a later except block. I have tried to implement this in code below, however it is not working.

 try:
   something
except SpecificError, ex:
   if str(ex) = "some error I am expecting"
      print "close softly"
   else:
      raise
except Exception, ex:
   print "did not close softly"
   raise

I want the raise in the else clause to trigger the final except statement.

How to catch the exception in a later except block?


1 Answer
Manogna

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.