Python | Algorithms | Data Structures | Cyber ​​Security | Networks
38.7K subscribers
778 photos
23 videos
21 files
712 links
This channel is for Programmers, Coders, Software Engineers.

1) Python
2) django
3) python frameworks
4) Data Structures
5) Algorithms
6) DSA

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
Download Telegram
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

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