906
try:
    something here
except:
    print('the whatever error occurred.')

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

Boris
  • 7,044
  • 6
  • 62
  • 63
TIMEX
  • 217,272
  • 324
  • 727
  • 1,038
  • 1
    Related: [How to print the full traceback without halting the program?](https://stackoverflow.com/q/3702675/3357935) – Stevoisiak Sep 19 '18 at 16:04

9 Answers9

1324

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
  • 526
  • 6
  • 16
jldupont
  • 82,560
  • 49
  • 190
  • 305
  • 62
    `str( KeyError('bad'))` => `'bad'` -- doesn't tell exception type – Dave Aug 28 '15 at 16:47
  • 22
    print(e) on keyerrors seems to give only the key, but not the full exception message, which is less than helpful. – Veggiet Feb 10 '19 at 13:03
  • 42
    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. – Martijn Pieters Oct 07 '19 at 09:55
  • You are right, but this prints only the exception text. This is often not useful to solve the problem that caused the exception. Thus I strongly prefer printing the traceback as in the solution below by @Cat Plus Plus! E.g. I had an issue with an invalid unicode character during XML parsing and printing the exception showed only "invalid character" or so. Not very helpful. The full trace showed "UnicodeEncodeError: character '\u2212' --> with this information I was able to fix the issue by searching for '\u2212' in my XML file. – Janis Aug 27 '20 at 13:28
  • 1
    @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 Dec 18 '20 at 11:10
  • 2
    @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. – Martijn Pieters Dec 24 '20 at 16:36
  • @MartijnPieters though you didn't, but you did recommend to use `print(repr(e))` specifically, whereas about the traceback you give some generic statement that it has various methods to print an exception. This sounds like you give preference to `repr()` way, and since your comment got so many upvotes, I thought it is worth writing a visible reply about what better method exists there. – Hi-Angel Dec 24 '20 at 18:38
  • 1
    @Hi-Angel I was focusing on printing _just_ the exception, and the traceback module has functions focusing on just the exception as well. – Martijn Pieters Dec 24 '20 at 19:56
550

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
  • 16,510
  • 19
  • 94
  • 173
Cat Plus Plus
  • 113,388
  • 26
  • 185
  • 215
  • 4
    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 Mar 27 '18 at 23:06
  • 29
    @MikeSchem ```error_message = traceback.format_exc()``` – heyzling Feb 08 '19 at 19:31
  • This snipped does not use the captured exception object. Can you expand the code to use 'ex'? - as in `except Exception as ex:`... – aaronsteers Aug 19 '19 at 19:42
  • 1
    @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. – Martijn Pieters Oct 07 '19 at 09:57
  • Yes, I would sometimes like to hold onto the exception and print it later, when I'm no longer in the 'except' block. – aaronsteers Oct 09 '19 at 16:55
  • Great answer, thank you so much! I was searching for ages for a way to get the whole exception text printed without actually throwing the exception. This is the solution :) In my case the exception text said "invalid character" which did not help. THe trace said "UnicodeEncodeError: can't encode character '\u2212'." --> with this infomration I could find and fix the issue quickly. Thanks again! :) – Janis Aug 27 '20 at 13:36
180

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
  • 18,333
  • 4
  • 38
  • 54
ilya n.
  • 16,814
  • 14
  • 66
  • 89
58

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
Nick Dandoulakis
  • 40,422
  • 14
  • 98
  • 136
52

(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.

grish
  • 761
  • 1
  • 6
  • 8
  • 2
    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. – Cameron Kerr Feb 11 '19 at 00:42
41

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, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

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 by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)
winklerrr
  • 6,735
  • 2
  • 45
  • 60
27

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'
GinTonic
  • 500
  • 4
  • 9
  • 5
    Wish I could upvote this answer many times, as it's significantly more helpful than the accepted one. – LarsH Aug 10 '20 at 16:01
  • 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. – pigeonburger Sep 09 '20 at 06:58
3

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
  • 16,510
  • 19
  • 94
  • 173
whatnick
  • 5,100
  • 2
  • 17
  • 35
0

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
Liam Roberts
  • 61
  • 1
  • 2