1. Basic Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
2. Catching Multiple Exceptions
try:
# some code
pass
except (TypeError, ValueError) as e:
print("Caught:", e)
3. Using else
and finally
try:
x = 5 / 1
except ZeroDivisionError:
print("Error!")
else:
print("No error occurred")
finally:
print("Always runs")
4. Catching All Exceptions (use with caution)
try:
risky_operation()
except Exception as e:
print("Caught error:", e)
5. Raising Exceptions
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
6. Custom Exceptions
class MyCustomError(Exception):
pass
raise MyCustomError("Something went wrong")
7. Common Built-in Exceptions
ZeroDivisionError
TypeError
ValueError
IndexError
KeyError
FileNotFoundError
AttributeError
ImportError
8. Suppressing Exceptions with contextlib
from contextlib import suppress
with suppress(FileNotFoundError):
open("nonexistent.txt")
9. Assertions
x = 10
assert x > 0, "x must be positive" # Raises AssertionError if condition is False