Exception
Exception is a built-in exception that serves as the base class for all built-in exceptions except for system-exiting exceptions.
It’s itself a direct subclass of BaseException. Exception is an important part of Python’s class hierarchy for exceptions, which helps you organize error handling in a structured way. Since Python 3.11, the built-in ExceptionGroup also derives from Exception, so an except Exception clause catches exception groups, while BaseExceptionGroup derives from BaseException and isn’t caught.
You’d typically use this exception as a base class for your own custom exceptions. By subclassing Exception, you ensure that your custom exceptions integrate smoothly with Python’s exception-handling mechanism. This allows you to handle errors and unexpected events effectively.
Exception Occurs When
The Exception class itself doesn’t appear unless you raise it explicitly.
Exception Can Be Used When
- Creating custom exceptions for your application
- Handling a broad range of exceptions in a single
exceptblock - Ensuring that exceptions integrate with Python’s built-in exception hierarchy
Exception Examples
It’s common to subclass Exception to create more specific exceptions:
>>> class CustomError(Exception):
... pass
...
>>> try:
... raise CustomError("This is a custom error")
... except CustomError as e:
... print(e)
...
This is a custom error
Below is a way to handle exceptions by catching them under a general Exception clause:
>>> import random
>>> def raise_random_error():
... errors = [
... ValueError("This is a ValueError"),
... TypeError("This is a TypeError"),
... IndexError("This is an IndexError")
... ]
... raise random.choice(errors)
...
>>> try:
... raise_random_error()
... except Exception as e:
... print(f"Caught an exception: {e}")
...
Caught an exception: This is a TypeError
The raise_random_error() function raises a random exception from the errors list. You can then handle any of these exceptions with a single except Exception block. This works because all of these exceptions inherit from Exception.
It’s recommended to raise and catch more specific exceptions instead of the Exception class. If you do catch Exception as a wildcard, the common pattern is to log the exception and then re-raise it so that callers can handle it too. Use a bare except Exception only when you really need a general-purpose error indicator.
Related Resources
Course
Using raise for Effective Exceptions
In this video course, you'll learn how to raise exceptions in Python, which will improve your ability to efficiently handle errors and exceptional situations in your code. This way, you'll write more reliable, robust, and maintainable code.
For additional information on related topics, take a look at the following resources:
- Working With Python's Built-in Exceptions (Course)
- Python Exceptions: An Introduction (Tutorial)
- Introduction to Python Exceptions (Course)
- KeyError Exceptions in Python and How to Handle Them (Course)
- Raising and Handling Python Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python Exceptions: An Introduction (Quiz)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.