Error Handling in Python
Learn how errors work in Python: runtime errors, exception types, try-except-finally, raising exceptions, custom exception classes, propagation, and stack traces.
Introduction to Errors
Errors (exceptions) occur when Python cannot execute code as expected. If not handled, the program stops immediately.
1. What is an Exception?
Runtime failure.
Common Exception Types
Python provides many built-in exception classes.
1. NameError
Undefined variable.
2. TypeError
Invalid operation on type.
3. ValueError
Invalid value.
4. ZeroDivisionError
Division by zero.
5. IndexError
Invalid list index.
try / except
try-except allows handling exceptions safely without crashing the program.
1. Basic try-except
Catch errors.
2. Access Exception Object
Capture error details.
3. Multiple except Blocks
Handle different errors differently.
finally Block
finally always runs whether exception occurs or not.
1. finally Execution
Cleanup code.
Raising Exceptions
raise allows manually triggering exceptions.
1. raise ValueError
Manual failure.
Custom Exception Classes
Custom exceptions improve clarity and allow domain-specific error handling.
1. Creating Custom Exception
Extend Exception.
Exception Propagation
Exceptions bubble up the call stack until handled.
1. Bubbling Example
Unhandled error travels upward.
Stack Trace & Traceback
Python prints a traceback when an exception is not handled.
1. What is a Traceback?
Execution history.
2. Using traceback Module
Programmatic stack access.