Python Exceptions
1. What is an Exception
An exception is an error that occurs during program execution and disrupts normal program flow.
print(10 / 0) # Raises ZeroDivisionErrorWithout handling, the program terminates immediately.
2. Basic try...except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")The try block contains risky code; except handles the error gracefully.
3. Handling Multiple Exceptions
try:
value = int("abc")
except ValueError:
print("Invalid conversion")
except ZeroDivisionError:
print("Division error")Different exception types can be handled separately.
4. Using else with try...except
The else block executes only if no exception is raised.
5. Using finally Block
finally always executes, whether an exception occurs or not.
6. Catching All Exceptions (Generic Exception)
Catches any exception; useful for logging but should be used cautiously.
7. Raising Custom Exceptions
The raise keyword triggers an exception manually.
8. Creating Custom Exception Classes
Custom exceptions improve clarity in domain-specific logic.
9. Using Assertions (assert)
Assertions are used for debugging and validation during development.
10. Best Practice: Structured Exception Handling
Encapsulating exception logic improves reliability and user experience.
Last updated