Aufwind
Aufwind

Reputation: 26278

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

Upvotes: 2

Views: 3535

Answers (4)

Daniel Backman
Daniel Backman

Reputation: 5241

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"

Upvotes: 1

Winston Ewert
Winston Ewert

Reputation: 45059

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.

Upvotes: 2

Dirk
Dirk

Reputation: 3093

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.

Upvotes: 4

Nathan Romano
Nathan Romano

Reputation: 7096

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

Upvotes: 4

Related Questions