简体   繁体   中英

How to catch message of finally exception clause in python?

I know how to catch exceptions and print the message they returned:

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e

This works good so far.

But how can I catch and print the message in a 'finally' clause?

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e
finally:
    # What goes here? So I can see what went wrong?

From several answers I understand, that this is not possible. Is it ok to do something like this?

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e
except Exception, e:
    # Hopefully catches all messages except for the one of MyDefinedException
    print "Unexpected Exception raised:", e

the code in the finally block will always be evaluated. check to see what went wrong in the catch block

According to the documentation , you can't:

The exception information is not available to the program during execution of the finally clause.

Best to check in the except block.

To catch anything at all use:

try:
    foo()
except:
    print sys.exc_info()
    raise

But this is almost always the wrong thing to do. If you don't what kind of exception happened there isn't anything you can do about it. If this happens your program should shut down and provide as much information as possible about what happened.

I needed similar thing but in my case to always cleanup some resources when no exception occurred. The below solution example worked for me and should also answer the question.

    caught_exception=None
    try:
      x = 10/0
      #return my_function()
    except Exception as e:
      caught_exception = e
    finally:
      if caught_exception:
         #Do stuff when exception
         raise # re-raise exception
      print "No exception"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM