close

How to print an exception in Python 3?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to print an exception in Python 3 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to print an exception in Python 3?

  1. How to print an exception in Python 3?

    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

  2. print an exception in Python 3

    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

Method 1

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.

Method 2

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”,)”

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read