Rob Lao
Rob Lao

Reputation: 1613

Is there a buildin(or 3rd party) function in Python to get the exception caught in context?

Is there a function in Python, e.g. get_exception, so I can do this:

try:
    can_raise_anything()
except:
    ex = *get_exception()*
    print('caught something: ' + str(ex))

I know in Python 3, I should use except BaseException as ex: to do the task. I'm just curious to see if there is a function can do that.

Upvotes: 0

Views: 120

Answers (2)

user2357112
user2357112

Reputation: 280301

except BaseException as e also works in Python 2.

If you really want to use a function for some reason, sys.exc_info() will return a tuple whose second element is the exception object. (The first element is the exception type, and the third element is the traceback.)

Upvotes: 2

Kroltan
Kroltan

Reputation: 5156

The except block can receive an additional part which looks like this:

try:
    stuff()
except Exception as e:
    print e

Some libraries (including builtin ones) provide specific Exception types, which can be used for reacting better depending to the type of error found. Combining this with the fact you can have as many except blocks for one try block, you can make a very fail-safe app. Example of a complex try-except block:

try:
    result = a / b
except TypeError as e:
    print "Woops! a and b must be numbers!"
    result = int(a) / int(b)
    print e
except NameError as e:
    print "A variable used doesn't exist!"
    print e
except ArithmeticError as e:
    print "It seems you've gone past infinity, under atomicity or divided by zero!"
    print e
except Exception as e:
    print "Something REALLY unexpected happened!"
    print e

Built-in exceptions used in the example:

  • TypeError: When the type of a variable is unexpected (e.g adding strings and numbers)
  • NameError: A variable used is not existant
  • ArithmeticError: General math error
  • Exception: Any kind of error, can be used for simple excepts or just for "everything else"

A list of built-in exceptions and their descriptions for Python 2.x can be found at http://docs.python.org/2/library/exceptions.html. Note: Usually custom libraries have comments describing the custom exceptions they raise.

Upvotes: 1

Related Questions