How to Print the Exception Without Exiting Your Python Program?

Problem Formulation

Given a basic Python program. How to print an exception if it occurs without exiting the program?

For example, consider the following program that raises a ZeroDivisionError: division by zero.

x = 42/0
print('Program is still running')

The output is:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 1, in <module>
    x = 42/0
ZeroDivisionError: division by zero

You want the program to keep running and executing the print statement after giving you a note about the exception:

division by zero
Program is still running

How to accomplish this in Python?

Basic Solution: Try/Except

An exception will immediately terminate your program. To avoid this, you can catch the exception with a try/except block around the code where you expect that a certain exception may occur. Here’s how you catch and print a given exception:

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e. You can now print the error message with "print(e)" or use it for further processing.

Here’s the general exception handling framework:

try:
    # ... YOUR CODE HERE ... #
except Exception as e:
    # ... PRINT THE ERROR MESSAGE ... #
    print(e)

In our particular example, you’d modify your program from …

x = 42/0
print('Program is still running')

… to …

try:
    x = 42/0
except Exception as e:
    print(e)

print('Program is still running')

Now, the output is your desired:

division by zero
Program is still running

Full Traceback Error Message

To print the full traceback of the error message—and keep the program running without exiting on an error—you can use a try/except block in combination with the traceback module’s format_exc() function.

  • Import the module with import traceback.
  • Print the full traceback of the error with print(traceback.format_exc()).

Here’s the full example code:

import traceback
import sys

try:
    x = 42/0
except Exception:
    print(traceback.format_exc())


print('Program is still running')

Now, the output shows the full traceback like so:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 5, in <module>
    x = 42/0
ZeroDivisionError: division by zero

Program is still running

The last line shows that the program doesn’t terminate when the exception occurs.

Summary

To print an exception without exiting the program, use a try/except block and assign the exception object to variable e using except Exception as e. Now, call print(e) in the except branch to print a simple error message.

If you need a more advanced error message with full traceback, import the traceback module and call print(traceback.format_exc()) in the except branch.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!