Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Last active Jan 20, 2020
Embed
What would you like to do?
Python Exception Reason PSA

I have often read the error message in a stacktrace and then reread it after I realized I was reading the code to produce the error message, rather than the error message itself. Often this will not matter, but if you are using a format string to produce the error message, I recommend putting the string generation on a separate line to the raise of the exception.

Variation 1, we have two lines with the error message/reason string, but only the last line one of them has the expanded format string (it includes 1234567890 which presumably is important).

$ python3 ../exception_format_string.py 1
Traceback (most recent call last):
  File "../exception_format_string_demo.py", line 6, in <module>
    raise Exception(f"My error message with formatting: '{arg}'")
Exception: My error message with formatting: '1234567890'

In variation 2, the stacktrace is easier to read, as it has only the expanded format string.

$ python3 ../exception_format_string.py 2
Traceback (most recent call last):
  File "../exception_format_string_demo.py", line 9, in <module>
    raise Exception(errmsg)
Exception: My error message with formatting: '1234567890'

The longer the error message, the more important this is.

import sys
arg = "1234567890"
if sys.argv[1] == "1":
raise Exception(f"My error message with formatting: '{arg}'")
else:
errmsg = f"My error message with formatting: '{arg}'"
raise Exception(errmsg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment