Python Exception Handling Cheat Sheet
Python Exception Handling Cheat Sheet
1.try-except Block:
Used to catch and handle exceptions.
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero!")
2.Multiple Exceptions:
Handle multiple exceptions in one except block.
try:
x = int("abc")
except (ValueError, TypeError):
print("Invalid type or value!")
3. else Block:
• Executes if no exception occurs.
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("No exceptions!")
4. finally Block:
• Always executes, useful for cleanup.
try:
file = open("test.txt")
except FileNotFoundError:
print("File not found")
finally:
print("Cleanup done")
5. raise Keyword:
• Used to manually raise exceptions.
if x < 0:
raise ValueError("Negative value!")
6. Custom Exceptions:
• Define custom exceptions by subclassing Exception.
class CustomError(Exception):
pass
raise CustomError("This is a custom error")