Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Python Exception Handling Cheat Sheet

Uploaded by

agammya27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Python Exception Handling Cheat Sheet

Uploaded by

agammya27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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")

You might also like