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 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.
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
except
block - 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 more specific exceptions instead of the Exception
class, but you can use Exception
if you need a general-purpose error indicator.
Related Resources
Tutorial
Python's Built-in Exceptions: A Walkthrough With Examples
In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.
For additional information on related topics, take a look at the following resources: