Raising and Handling Exceptions in Python: A Complete Guide

8/17/2025

Examples of raising and handling exceptions in Python applications like file handling and API requests

Go Back

Raising and Handling Exceptions in Python: A Complete Guide

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.


Examples of raising and handling exceptions in Python applications like file handling and API requests

What are Exceptions in Python?

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.


Raising Exceptions in Python

You can use the raise keyword to trigger an exception manually.

Example 1: Raising a Built-in Exception

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.


Example 2: Raising Custom Exceptions

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.


Handling Exceptions in Python

To prevent your program from crashing, you can use try-except blocks.

Example 3: Handling Raised Exceptions

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.


Example 4: Using Try-Except-Else-Finally

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.


Best Practices for Raising and Handling Exceptions

  1. Raise specific exceptions – Use built-in exceptions or custom ones instead of generic Exception.

  2. Keep try blocks small – Only include code that might raise an error.

  3. Use meaningful error messages – Make debugging easier with descriptive messages.

  4. Log exceptions – Use Python’s logging module for production apps instead of just printing errors.

  5. Don’t suppress errors silently – Always handle them properly.


Real-World Use Cases

  • 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.


Conclusion

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.

Table of content