In Python, exceptions are events that represent an error, and that interrupt the normal flow of execution of a program.
Exceptions are used to signal exceptional conditions that require special handling (for example, division by zero, referencing an undefined variable, or opening a file that does not exist).
Some of the features of exceptions are:
- Interruption of normal flow: Exceptions alter the normal flow of the program.
- Custom exceptions: Allow for specific and controlled error handling.
- Inheritance of exceptions: Exceptions in Python are classes (this allows for the creation of exception hierarchies).
Base Exceptions
In Python, all exceptions inherit from base exceptions,
- Exception: Base class for all exceptions in Python, except those that indicate interpreter exit.
- BaseException: Base class for all exceptions, including those used to control program termination.
Standard Exceptions in Python
Python includes a large number of standard exceptions that cover various errors and exceptional conditions. Here is a list of some of the most common standard exceptions.
Runtime Error Exceptions
try:
result = 1 / 0
except ZeroDivisionError as e:
print(f"Division by zero error: {e}")
- ArithmeticError: Base class for numerical errors.
- ZeroDivisionError: Raised when attempting to divide by zero.
- OverflowError: Raised when a numerical calculation exceeds the maximum limit allowed.
- FloatingPointError: Raised when an error occurs in a floating-point operation.
Input/Output Operation Exceptions
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError as e:
print(f"File not found: {e}")
- IOError: Base class for input/output errors.
- FileNotFoundError: Raised when a file or directory is not found.
- PermissionError: Raised when an operation does not have the proper permissions.
Argument Exceptions
try:
number = int("abc")
except ValueError as e:
print(f"Value error: {e}")
- TypeError: Raised when an operation or function is applied to an inappropriate type of object.
- ValueError: Raised when an operation or function receives an argument of the correct type but an inappropriate value.
Variable and Attribute Exceptions
try:
print(undefined_variable)
except NameError as e:
print(f"Variable name not found: {e}")
- NameError: Raised when a local or global variable is not found.
- AttributeError: Raised when attempting to access an attribute that does not exist in an object.
System Exceptions
- SystemError: Raised when an internal error in Python is detected.
- KeyboardInterrupt: Raised when the program execution is interrupted by user input (for example, Ctrl+C).