Exception Basics
What are Exceptions?
Exceptions in Python are events that occur during program execution which disrupt the normal flow of instructions. They are used to handle errors and unexpected situations gracefully.
Basic Exception Handling Structure
In Python, exceptions are managed using try
, except
, else
, and finally
blocks:
try:
## Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
## Handle specific exception
print(f"Error occurred: {e}")
else:
## Execute if no exception occurs
print("Operation successful")
finally:
## Always execute, regardless of exception
print("Cleanup operations")
Common Built-in Exceptions
Exception Type |
Description |
ValueError |
Raised when an operation receives an inappropriate argument |
TypeError |
Occurs when an operation is performed on an incompatible type |
ZeroDivisionError |
Raised when dividing by zero |
FileNotFoundError |
Occurs when trying to access a non-existent file |
Exception Hierarchy
graph TD
A[BaseException] --> B[SystemExit]
A --> C[KeyboardInterrupt]
A --> D[Exception]
D --> E[ArithmeticError]
D --> F[TypeError]
D --> G[ValueError]
Raising Custom Exceptions
You can create and raise your own exceptions:
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def validate_age(age):
if age < 0:
raise CustomError("Age cannot be negative")
Best Practices
- Be specific with exception handling
- Avoid catching all exceptions with bare
except
- Use meaningful error messages
- Log exceptions for debugging
At LabEx, we recommend understanding exception mechanics to write more robust Python code.