How to print an exception in Python 3? How to print an exception in Python 3? python-3.x python-3.x

How to print an exception in Python 3?


I'm guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:

def fails():    x = 1 / 0try:    fails()except Exception as ex:    print(ex)

To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.

In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try Statement.)


The other compound statement using as is the with statement:

@contextmanagerdef opening(filename):    f = open(filename)    try:        yield f    finally:        f.close()with opening(filename) as f:    # ...read data from f...

Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use.(This is discussed in detail in the Python 3 Language Reference: The with Statement.)


Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:

import foo.bar.baz as fbb

This is discussed in detail in the Python 3 Language Reference: The import Statement.


These are the changes since python 2:

    try:        1 / 0    except Exception as e: # (as opposed to except Exception, e:)                           # ^ that will just look for two classes, Exception and e        # for the repr        print(repr(e))        # for just the message, or str(e), since print calls str under the hood        print(e)        # the arguments that the exception has been called with.         # the first one is usually the message. (OSError is different, though)        print(e.args)

You can look into the standard library module traceback for fancier stuff.


Try

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

this will print the representation given by e.__str__():

"name 'undefined_var' is not defined"

you can also use:

print(repr(e))

which will include the Exception class name:

"NameError("name 'undefined_var' is not defined",)"