As a Python developer, you‘ll inevitably encounter errors or exceptions in your code. Knowing how to properly handle and print these exceptions is an essential skill. In this comprehensive guide, I‘ll cover several methods for printing exception messages in Python.
What Are Exceptions in Python?
Exceptions, or errors, occur when Python encounters a problem during execution. This could be due to invalid syntax, an invalid operation, file input/output errors, and many other issues.
When an exception occurs, Python generate an exception object and ends current execution of the program. If not properly handled, our program will crash. However, we can "catch" exceptions and take appropriate actions through exception handling.
For example:
x = 10
print(x / 0)
This will cause a ZeroDivisionError, as we can‘t divide by zero.
Here‘s what the exception error message will look like:
Traceback (most recent call last):
File "script.py", line 2, in <module>
print(x / 0)
ZeroDivisionError: division by zero
This provides information trace of where the error occurred along with exception type and message.
Why Print Exceptions in Python?
Printing exceptions serves two key purposes:
-
It allows you to display a user-friendly error message when an error occurs
-
It helps debug errors by showing exception information like type, message, and stack trace
Useful for identifying issues during development. Also helpful for logging errors in production applications.
Now let‘s explore several methods for printing exceptions in Python.
Method 1: The print() Function
The simplest way to print an exception in Python is using the print() function.
Here is an example:
try:
num = 10 / 0
except Exception as ex:
print(‘Error occurred:‘, ex)
- We use a try/except block to catch exceptions
- In the except block, we print a custom message
- We also print the exception instance using
print(ex)
This will output:
Error occurred: division by zero
We can also print just the exception message:
print(‘Error:‘, ex.__str__())
Output:
Error: division by zero
The print() function is great for simple cases when you just need to display the exception.
Downsides:
- Doesn‘t include traceback info
- Output may be lost if not run from console
Method 2: The logging Module
The logging module in Python provides more robust logging capabilities. It allows writing log messages to files, sending emails, and other useful features.
To print exceptions with logging:
import logging
try:
10 / 0
except Exception as ex:
logging.error("Exception occurred", exc_info=True)
This will output:
ERROR:root:Exception occurred
Traceback (most recent call last):
File "script.py", line 4, in <module>
10 / 0
ZeroDivisionError: division by zero
The key things here:
- Import the
loggingmodule - Call
logging.error()to log exception - Pass
exc_info=Trueto include traceback info
We can also customize the formatting and where logs are written to.
Some advantages over print():
- Logs traceback to help debug issue
- Flexibility in output format and locations
- Can log exceptions without crashing application
Overall, logging provides a more versatile way to print exceptions in Python.
Method 3: The traceback Module
The traceback module contains helpful functions for working with call stacks and tracebacks when debugging.
To print a full exception traceback, we can do:
import traceback
try:
10 * ‘2‘
except:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "script.py", line 4, in <module>
10 * ‘2‘
TypeError: unsupported operand type(s) for *: ‘int‘ and ‘str‘
This prints the full stack trace starting from the last call. Very useful when trying to diagnose tricky exception causes.
We can also format the output:
traceback.print_exc(limit=2, file=sys.stdout)
This will print just the last two lines of the traceback.
Key things about traceback method:
- Simple way to get full stack printout
- Flexible formatting options
- Includes exception type and message
Overall, an easy way to get a traceback string when printing exceptions in Python.
Method 4: Raising Exceptions
In addition to handling exceptions, we can also manually raise them with the raise keyword.
For example:
def validate(age):
if age < 0:
raise ValueError("Age cannot be negative")
return True
try:
validate(-5)
except ValueError as ex:
print(ex)
This prints:
Age cannot be negative
Why manually raise exceptions?
Some reasons:
- Validate input data and arguments
- Signal errors from deep inside nested code
- Force errors for testing exception handling
We can customize exception messages this way.
Method 5: Custom Exception Classes
For more complex programs, it‘s often useful to define our own custom application exception classes.
This allows customizing exception types and messages.
Example:
class InvalidAgeException(Exception):
pass
def validate(age):
if age < 0:
raise InvalidAgeException(‘Entered age is negative‘)
try:
validate(-5)
except InvalidAgeException as ex:
print(ex)
Output:
Entered age is negative
Benefits of custom exceptions:
- Descriptive names for our exception types
- Custom data can be passed along
- Cleaner way to signal errors from our code
This allows other developers to easily identify and handle domain-specific exceptions from our modules and libraries.
Best Practices
When printing exceptions in Python, keep these best practices in mind:
- Don‘t silence exceptions entirely – this hides errors
- Catch specific exception types instead of bare
exceptblocks whenever possible - Print useful error messages for end users but log full tracebacks for debugging
- Raise descriptive errors from functions and libraries
- Use exception chaining when wrapping lower-level exceptions
- Document expected exceptions in docstrings and comments
Conclusion
Handling and printing exceptions properly is critical for writing robust Python code.
Key takeaways:
- Use
print()andraisefor simple cases - Log exceptions with the
loggingmodule for larger applications - Print tracebacks with
tracebackwhen debugging - Raise custom exception classes to signal errors
- Follow best practices around reporting and documenting exceptions
With these exception handling techniques, you‘ll be able to write Python code that anticipates and gracefully recovers from unexpected situations.
Let me know if you have any other questions!


