
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Cleaner Way to Handle Python Exceptions
Python uses the try-except block to handle errors during runtime. But as your program grows, handling exceptions can get messy with repeated code or too many nested blocks.
Using cleaner methods for exception handling can reduce duplication, and make your code easier to manage. In this article, we explore better ways to handle exceptions in Python.
Using Specific Exception Types
It is best to catch specific exceptions like ValueError or FileNotFoundError instead of using a general except: block. This prevents hiding unexpected errors and improves debugging
This approach avoids catching unrelated exceptions like KeyboardInterrupt or TypeError.
Example
In this example, only ValueError is caught, and other unexpected errors are not silently ignored -
try: number = int(input("Enter an integer: ")) print("Square is:", number ** 2) except ValueError: print("Invalid input. Please enter a valid integer.")
Following is the output obtained -
Enter an integer: t Invalid input. Please enter a valid integer.
Using Exception Chaining
Use the raise ... from ... syntax to raise a new exception while keeping the original one as context. This helps you trace back to the root cause of an error, making debugging easier and more informative.
Example
In the following example, we re-raise an exception with a custom message while preserving the original traceback.
# Step 1: Create the file with an integer value with open("data.txt", "w") as f: f.write("4b") # You can change this to any integer value # Step 2: Function to read the number def read_number(file_path): try: with open(file_path) as f: return int(f.read()) except ValueError as e: raise RuntimeError("Failed to read a valid integer from file") from e # Step 3: Use the function and handle errors try: value = read_number("data.txt") print("Read value:", value) except RuntimeError as e: print("Error:", e)
We get the output as shown below -
Error: Failed to read a valid integer from file
Grouping Multiple Exceptions
You can handle different types of exceptions in a single except block by listing them in a tuple. This keeps your code cleaner and avoids writing separate blocks for each exception type.
Example
Here, we are grouping ValueError and TypeError exceptions together in a single except block -
try: number = int("abc") except (ValueError, TypeError) as e: print("Conversion failed:", e)
The error obtained is as shown below -
Conversion failed: invalid literal for int() with base 10: 'abc'
Creating Reusable Error-Handling Functions
Instead of writing the same try-except logic multiple times, you can create a helper function or use a decorator to handle errors in one place. This makes your code more reusable, cleaner, and easier to update when handling exceptions.
This pattern is useful when you want uniform exception logging for multiple functions.
Example
This following function wraps another function and provides consistent error handling in one place -
def safe_run(func): try: return func() except Exception as e: print("Error occurred:", e) def divide(): return 10 / 0 safe_run(divide)
The reult produced is as follows -
Error occurred: division by zero