How do I print an exception in Python?
For Python 2.6 and later and Python 3.x:
except Exception as e: print(e)
For Python 2.5 and earlier, use:
except Exception,e: print str(e)
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 / 0
try:
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.)
There are other compound statements that use as
. The first is the with
statement:
@contextmanager
def 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.)
As of Python 3.10, match
statements also use as
:
from random import randint
match randint(0, 2):
case 0|1 as low:
print(f"{low} is a low number")
case _:
print("not a low number")
match
statements take an expression (in this case, randint(0, 2)
) and compare its value to each case
branch one at a time until one of them succeeds, at which point it executes that branch's block. In a case
branch, as
can be used to assign the value of the branch to a variable if that branch succeeds. If it doesn't succeed, it is not bound.
(The match
statement is covered by the tutorial and discussed in detail in the Python 3 Language Reference: match
Statements.)
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.
How to print an exception?
Use traceback module:
try:
action()
except:
import traceback
traceback.print_exc()
How to catch and print the full exception traceback without halting/exiting the program?
Some other answer have already pointed out the traceback module.
Please notice that with print_exc
, in some corner cases, you will not obtain what you would expect. In Python 2.x:
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
...will display the traceback of the last exception:
Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info
in a local variable and display it using print_exception
:
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
Producing:
Traceback (most recent call last):
File "t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
Few pitfalls with this though:
From the doc of
sys_info
:Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)
but, from the same doc:
Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
... will display:
File "e3.py", line 4, in <module>
raise TypeError("Oups!")
Line number in Python exception
import traceback
try:
print("a" + 1)
except Exception as e:
print("There was an error: " + e.args[0] + ". The line where the code failed was " + str(traceback.extract_stack()[-1][1]))
How to get exception message in Python properly
If you look at the documentation for the built-in errors, you'll see that most Exception
classes assign their first argument as a message
attribute. Not all of them do though.
Notably,EnvironmentError
(with subclasses IOError
and OSError
) has a first argument of errno
, second of strerror
. There is no message
... strerror
is roughly analogous to what would normally be a message
.
More generally, subclasses of Exception
can do whatever they want. They may or may not have a message
attribute. Future built-in Exception
s may not have a message
attribute. Any Exception
subclass imported from third-party libraries or user code may not have a message
attribute.
I think the proper way of handling this is to identify the specific Exception
subclasses you want to catch, and then catch only those instead of everything with an except Exception
, then utilize whatever attributes that specific subclass defines however you want.
If you must print
something, I think that printing the caught Exception
itself is most likely to do what you want, whether it has a message
attribute or not.
You could also check for the message attribute if you wanted, like this, but I wouldn't really suggest it as it just seems messy:
try:
pass
except Exception as e:
# Just print(e) is cleaner and more likely what you want,
# but if you insist on printing message specifically whenever possible...
if hasattr(e, 'message'):
print(e.message)
else:
print(e)
How to print the exception string in class for Python
To get the full path of an exception, use the inspect.getmodule method to get the package name and use type(..).__name __ to get the class name.
except WebDriverException as ex:
print (type(ex).__name__)
For the full name, try
import inspect
.....
print(inspect.getmodule(ex).__name__, type(ex).__name__, sep='.')
To keep it simple, you can just parse the string you already have
print(str(sys.exc_info()[0])[8:-2]) # selenium.common.exceptions.SessionNotCreatedException
How to print every error using try except in python
As the IndexError
occurs, it goes to the except
, so the 4/0
is not executed, the ZeroDivisionError
doesn't occur, to get both executed, use 2 different try-except
try:
a = [1, 2]
print(a[3])
except IndexError as e:
print(e)
try:
4 / 0
except ZeroDivisionError as e:
print(e)
Giving
list index out of range
division by zero
Related Topics
Finding Indices of Matches of One Array in Another Array
Is There a Math Ncr Function in Python
Function for Factorial in Python
What Is the Quickest Way to Http Get in Python
Working with Big Data in Python and Numpy, Not Enough Ram, How to Save Partial Results on Disc
Subprocess.Call Using String VS Using List
Python Unicodedecodeerror - am I Misunderstanding Encode
How to Split and Parse a String in Python
Pandas: Converting to Numeric, Creating Nans When Necessary
In Python, Differencebetween ".Append()" and "+= []"
Pandas Groupby Multiple Fields Then Diff
Replacing Few Values in a Pandas Dataframe Column with Another Value
Selecting a Row of Pandas Series/Dataframe by Integer Index
Python Sharing a Lock Between Processes
How to Make Program Go Back to the Top of the Code Instead of Closing