⚠️ Python Try–Except — Handling Errors Gracefully
Introduction 🌟
Python’s try–except block lets you handle runtime errors gracefully instead of crashing your program. This is essential for writing safe, professional, and user-friendly applications.
Note
💡 Errors are normal — good code **handles** them, not avoids them.
1. Basic try–except Structure 🧱
basic_try_except.py
try:
risky_code()
except:
print("Something went wrong!")✔ The code inside try runs first.
✔ If an error occurs → jump to except.
2. Catching Specific Exceptions 🎯
specific_exception.py
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")Note
✔ Always prefer catching **specific** errors instead of using a broad
except:.3. Multiple Except Blocks 🧩
multiple_except.py
try:
x = int("abc")
except ValueError:
print("Invalid integer!")
except TypeError:
print("Wrong type used!")4. Catching Multiple Exceptions in One Line 🔗
multiple_in_one.py
try:
num = int(input("Enter number: "))
except (ValueError, TypeError):
print("Invalid input!")5. Using else Block ✨
else runs only if try has **no errors**.
try_except_else.py
try:
result = 10 / 2
except ZeroDivisionError:
print("Error occurred")
else:
print("Success! Result =", result)6. Using finally Block 🧹
finally runs **always**, whether an error occurs or not. Useful for cleanup actions like closing files or disconnecting databases.
try_except_finally.py
try:
file = open("data.txt")
data = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file...")
# file.close()7. Combining try–except–else–finally 🎛️
full_combination.py
try:
x = int("10")
except ValueError:
print("Conversion error")
else:
print("Converted:", x)
finally:
print("Done")8. Accessing the Error Message 📝
exception_as.py
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)✔ Useful for logging detailed error information.
9. Raising Your Own Exceptions 🚨
raise_exception.py
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")10. Try–Except Inside Functions 🧠
try_in_function.py
def safe_div(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
print(safe_div(10, 2))
print(safe_div(10, 0))11. Nested Try–Except 🔁
nested_try.py
try:
try:
num = int("abc")
except ValueError:
print("Inner block caught error")
except Exception:
print("Outer block caught error")12. Real-World Example: User Input Validation 🔤
input_validation.py
while True:
try:
age = int(input("Enter age: "))
break
except ValueError:
print("Please enter a valid number!")13. Real-World Example: File Handling 📁
file_try_except.py
try:
with open("notes.txt") as f:
print(f.read())
except FileNotFoundError:
print("File missing!")14. Best Practices 💡
- ✔ Catch specific exceptions
- ✔ Use
finallyfor cleanup operations - ✔ Never write empty
except:blocks - ✔ Keep try blocks small
- ✔ Log errors during debugging
Conclusion 🎉
>>“Try–Except gives your program resilience — errors stop being crashes and become controllable events.” ✨
You now fully understand Try–Except in Python! Want the next topic? Try Exception Types, Raising Errors, Custom Exceptions, or File Handling. Just tell me! 😊