Raising and Handling Exceptions in Python: A Complete Guide
Examples of raising and handling exceptions in Python applications like file handling and API requests
When writing Python programs, errors are inevitable. Sometimes, you need to deliberately raise an error to indicate that something went wrong. Python provides a robust system for raising and handling exceptions to make applications more reliable and easier to debug.
In this article, we’ll explore how to raise exceptions, handle them with try-except blocks, and follow best practices with examples.
Exceptions are special objects in Python that represent errors. When an error occurs, Python generates an exception that interrupts the normal flow of the program. If not handled, the program will terminate.
For example:
x = 10 / 0
This raises a ZeroDivisionError
and stops the program.
You can use the raise keyword to trigger an exception manually.
x = -5
if x < 0:
raise ValueError("Value cannot be negative!")
Output:
ValueError: Value cannot be negative!
✅ Here, we explicitly raised a ValueError
when the condition was met.
You can also create your own exceptions by defining a class that inherits from the Exception
class.
class NegativeNumberError(Exception):
pass
x = -10
if x < 0:
raise NegativeNumberError("Custom Error: Negative numbers are not allowed!")
Output:
NegativeNumberError: Custom Error: Negative numbers are not allowed!
✅ This allows developers to define domain-specific errors.
To prevent your program from crashing, you can use try-except blocks.
try:
num = int("abc")
except ValueError as e:
print("Caught an exception:", e)
Output:
Caught an exception: invalid literal for int() with base 10: 'abc'
✅ The program continues instead of stopping.
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
else:
print("Valid number entered:", num)
finally:
print("Execution finished.")
try → runs risky code.
except → catches exceptions.
else → runs if no exception occurs.
finally → always runs, useful for cleanup operations.
Raise specific exceptions – Use built-in exceptions or custom ones instead of generic Exception
.
Keep try blocks small – Only include code that might raise an error.
Use meaningful error messages – Make debugging easier with descriptive messages.
Log exceptions – Use Python’s logging
module for production apps instead of just printing errors.
Don’t suppress errors silently – Always handle them properly.
Input validation – Ensuring user inputs are valid.
File handling – Raising FileNotFoundError
when a file is missing.
API requests – Handling timeouts or invalid responses.
Database operations – Raising errors when queries fail.
Understanding how to raise and handle exceptions in Python is crucial for building robust and professional applications. By raising meaningful exceptions and handling them with try-except blocks, you can prevent crashes and improve user experience.