1509

How do I print the error/exception in the except: block?

try:
 ...
except:
 print(exception)
Mateen Ulhaq
27.7k21 gold badges120 silver badges155 bronze badges
asked Sep 27, 2009 at 11:48
2

11 Answers 11

2029

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)
Jan
5567 silver badges16 bronze badges
answered Sep 27, 2009 at 12:19
Sign up to request clarification or add additional context in comments.

8 Comments

str( KeyError('bad')) => 'bad' -- doesn't tell exception type
print(e) on keyerrors seems to give only the key, but not the full exception message, which is less than helpful.
If you are going to print the exception, it is better to use print(repr(e)); the base Exception.__str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.
@MartijnPieters the print(repr(e)) doesn't give any stracktrace. The print_exc from traceback module (mentioned in the other answer) though works in this case.
@Hi-Angel: Where am I claiming that printing repr(e) would give the stack trace? I'm talking about the difference between str(e) and repr(e), the latter includes more information that you would also see in the last line(s) of a traceback. I explicitly mention the traceback module in my comment.
|
834

The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

import traceback
try:
 1/0
except Exception:
 traceback.print_exc()

Output:

Traceback (most recent call last):
 File "C:\scripts\divide_by_zero.py", line 4, in <module>
 1/0
ZeroDivisionError: division by zero
Stevoisiak
27.7k32 gold badges138 silver badges245 bronze badges
answered Sep 27, 2009 at 12:25

8 Comments

is there some kind of get_error_message call that I can print with seeing as I'm using my own printing routine to add some other things.
@MikeSchem error_message = traceback.format_exc()
This snipped does not use the captured exception object. Can you expand the code to use 'ex'? - as in except Exception as ex:...
@aaronsteers it does use the captured exception; in an exception handler the current exception is available via the sys.exc_info() function and the traceback.print_exc() function gets it from there. You’d only ever need to pass in an exception explicitly when not handling an exception or when you want to show info based on a different exception.
Yes, I would sometimes like to hold onto the exception and print it later, when I'm no longer in the 'except' block.
|
202

In Python 2.6 or greater it's a bit cleaner:

except Exception as e: print(e)

In older versions it's still quite readable:

except Exception, e: print e
Max
22.5k7 gold badges54 silver badges79 bronze badges
answered Sep 27, 2009 at 16:42

1 Comment

This solution was exactly said above! (see previous ones then write)
144

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, for example, logging messages...

  • into a given log file, or
  • with timestamps and additional information about where the logging happened.

For more information check out the official documentation.


Usage

Logging an exception can be done with the module-level function logging.exception() like so:

import logging
try:
 1/0
except BaseException:
 logging.exception("An exception was thrown!")

Output

ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
 1/0
ZeroDivisionError: division by zero 

Notes

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log level but still show the exception details by using the keyword argument exc_info=True, like so:

logging.critical("An exception was thrown!", exc_info=True)
logging.error ("An exception was thrown!", exc_info=True)
logging.warning ("An exception was thrown!", exc_info=True)
logging.info ("An exception was thrown!", exc_info=True)
logging.debug ("An exception was thrown!", exc_info=True)
# or the general form
logging.log(level, "An exception was thrown!", exc_info=True)

Name and description only

Of course, if you don't want the whole traceback but only some specific information (e.g., exception name and description), you can still use the logging module like so:

try:
 1/0
except BaseException as exception:
 logging.warning(f"Exception Name: {type(exception).__name__}")
 logging.warning(f"Exception Desc: {exception}")

Output

WARNING:root:Exception Name: ZeroDivisionError
WARNING:root:Exception Desc: division by zero
Benjamin Loison
5,7314 gold badges19 silver badges37 bronze badges
answered Oct 30, 2019 at 9:22

4 Comments

Should not be used inside a logging handler to avoid RecursionError
In this example, the exception is logged and the exception is "handled". One may wish to re-raise this exception, if not sufficiently handled.
This "logging.exception()" is great! It has alwas worked well for me. When I, instead, logged "Exception" or anything in the other answers, sometimes it worked well, sometimes it printed another "error", sometimes it did not tell the filename and line number of the error, and sometimes it logged a wrong file and line number.
Excepting BaseException may be risky. See note for KeyboardInterrupt at the official documentation: docs.python.org/3/library/exceptions.html#KeyboardInterrupt
98

Expanding off of the "except Exception as e:" solution here is a nice one liner which includes some additional info like the type of error and where it occurred.

try:
 1/0
except Exception as e:
 print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")

Output:

ZeroDivisionError at line 48 of /Users/.../script.py: division by zero
Benjamin Loison
5,7314 gold badges19 silver badges37 bronze badges
answered Apr 15, 2021 at 16:15

8 Comments

The most useful answer.
for me pint(e) only returns Message: nothing else in python 3.7 anaconda
had to scroll down too far to get the real answer.
It is maybe useful for the sake of example to know where to grab the information of the exception, but it is really clumsy if you think to handle all exceptions this way.
@JayZee, not clumsy if you write a function consisting of the print line in the answer and just pass the exception to that function from every exception block.
|
89

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
 print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
 print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

Benjamin Loison
5,7314 gold badges19 silver badges37 bronze badges
answered Sep 21, 2018 at 19:38

2 Comments

I would suggest further adding flush=True. I've noticed with systemd (and not using a proper logging framework), that buffering when capturing to the journal is not what I would have expected.
@CameronKerr isn’t ‘stderr’ not buffered?
73

In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)

>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
answered Sep 27, 2009 at 11:56

Comments

73

One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.

The code

with open("not_existing_file.txt", 'r') as text:
 pass

would produce the following traceback:

Traceback (most recent call last):
 File "exception_checks.py", line 19, in <module>
 with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/Log the full traceback

As others already mentioned, you can catch the whole traceback by using the traceback module:

import traceback
try:
 with open("not_existing_file.txt", 'r') as text:
 pass
except Exception as exception:
 traceback.print_exc()

This will produce the following output:

Traceback (most recent call last):
 File "exception_checks.py", line 19, in <module>
 with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

You can achieve the same by using logging:

try:
 with open("not_existing_file.txt", 'r') as text:
 pass
except Exception as exception:
 logger.error(exception, exc_info=True)

Output:

__main__: 2020年05月27日 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
 File "exception_checks.py", line 27, in <module>
 with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/log error name/message only

You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:

try:
 with open("not_existing_file.txt", 'r') as text:
 pass
except Exception as exception:
 print("Exception: {}".format(type(exception).__name__))
 print("Exception message: {}".format(exception))

Output:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
answered Apr 15, 2020 at 10:10

3 Comments

Wish I could upvote this answer many times, as it's significantly more helpful than the accepted one.
With the last section in your answer ('Print/log error name\message only') how can I print both Exception and Exception Message using print only once? Whenever I try to do it, it turns out all weird.
print(f"Exception: {type(exception).__name__}\nException message: {exception}"). The f at the beginning signifies that it is an f-string, which just allows you to put the expression in the curly braces instead of using .format(). f-strings only work on systems running Python 3.6+ however
40

Try this

try:
 print("Hare Krishna!")
except Exception as er:
 print(er)
vvvvv
32.8k19 gold badges69 silver badges103 bronze badges
answered Feb 20, 2022 at 7:57

1 Comment

Usually a code block with no explanation is not a very good answer. It helps the community much more if you could tell us why we should try this code and why it would/might help the op. Thanks!
6

I would recommend using a try-except statement. Also, rather than using a print statement, a logging exception logs a message with level ERROR on the logger, which I find is more effective than a print output. This method should only be called from an exception handler, as it is here:

import logging
try:
 *code goes here*
except BaseException:
 logging.exception("*Error goes here*")

There's good documentation on this python page if you want to learn more about logging and debugging.

answered Jul 29, 2021 at 14:11

1 Comment

Its difficult to judge in the repl, am I correct in thinking that this prints the exception but does not halt the program? I.e. I can still gracefully exit.
4

One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.

assert type(A) is type(""), "requires a string"
Stevoisiak
27.7k32 gold badges138 silver badges245 bronze badges
answered Sep 27, 2009 at 15:38

1 Comment

assert statements should not be used for normal logic; they are ignored if python runs with -O. See python(1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.