Basic Exception Handling
try:
1 / 0
except Exception as e:
print(f"{type(e).__name__}: {e}")
# Output: ZeroDivisionError: division by zero
Catching Specific Exceptions
try:
x = int("abc")
except ValueError as e:
print(f"ValueError: {e}")
Using else and finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
finally:
print("This block always executes.")
Raising Exceptions
def divide(a, b):
if b == 0:
raise ValueError("b cannot be zero")
return a / b
Best Practices
- Catch specific exceptions when possible.
- Use
finally for cleanup actions (e.g., closing files).
- Avoid catching
Exception unless necessary.
- Use informative error messages.
References