Topic: Python Exception Handling — Managing Errors Gracefully
---
Why Handle Exceptions?
• To prevent your program from crashing unexpectedly.
• To provide meaningful error messages or recovery actions.
---
Basic Try-Except Block
---
Catching Multiple Exceptions
---
Using Else and Finally
• else block runs if no exceptions occur.
• finally block always runs, used for cleanup.
---
Raising Exceptions
• You can raise exceptions manually using raise.
---
Custom Exceptions
• Create your own exception classes by inheriting from Exception.
---
Summary
• Use try-except to catch and handle errors.
• Use else and finally for additional control.
• Raise exceptions to signal errors.
• Define custom exceptions for specific needs.
---
#Python #ExceptionHandling #Errors #Debugging #ProgrammingTips
---
Why Handle Exceptions?
• To prevent your program from crashing unexpectedly.
• To provide meaningful error messages or recovery actions.
---
Basic Try-Except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
---
Catching Multiple Exceptions
try:
x = int(input("Enter a number: "))
result = 10 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
---
Using Else and Finally
• else block runs if no exceptions occur.
• finally block always runs, used for cleanup.
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
file.close()
---
Raising Exceptions
• You can raise exceptions manually using raise.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
check_age(-1)
---
Custom Exceptions
• Create your own exception classes by inheriting from Exception.
class MyError(Exception):
pass
def do_something():
raise MyError("Something went wrong!")
try:
do_something()
except MyError as e:
print(e)
---
Summary
• Use try-except to catch and handle errors.
• Use else and finally for additional control.
• Raise exceptions to signal errors.
• Define custom exceptions for specific needs.
---
#Python #ExceptionHandling #Errors #Debugging #ProgrammingTips
❤2