Python Try...Except 🛡️
Handling Errors Gracefully
Exception handling allows you to manage runtime errors without crashing your program. Use try, except, else, and finally blocks.
🎈 Analogy: The Airbag
Think of a try...except block as an Airbag in a car.
- Normal Driving (Try): You drive along, hoping nothing happens.
- Crash (Exception): If you hit something, the airbag deploys (Except block runs) to save you.
- Without it, the car (program) would be totally destroyed (crash).
✨ Basic Structure
try:
# Code that might raise an exception
print(x)
except NameError:
# Handle specific error
print("Variable x is not defined")
except Exception as e:
# Handle any other error
print(f"An error occurred: {e}")
else:
# Runs if NO exception occurs
print("Success!")
finally:
# Always runs (cleanup)
print("Finished")🎯 Real-World Application: Network Requests
When fetching data from the internet, things often go wrong (offline, server down). You must handle this gracefully.
import requests
try:
response = requests.get("https://api.example.com/data")
response.raise_for_status() # Check for HTTP errors
print(response.json())
except requests.exceptions.ConnectionError:
print("⚠️ No internet connection!")
except requests.exceptions.Timeout:
print("⚠️ Request timed out!")
except Exception as e:
print(f"⚠️ Something went wrong: {e}")🚀 Raising Exceptions
You can manually trigger exceptions using the raise keyword. This is useful for enforcing constraints.
x = -1
if x < 0:
raise ValueError("Sorry, no numbers below zero")🛠️ Custom Exceptions
You can create your own exception classes by inheriting from the built-in Exception class.
class InvalidAgeError(Exception):
pass
age = 150
if age > 120:
raise InvalidAgeError("Age is too high!")⚠️ Watch Out!
Avoid using a bare except: clause. It catches ALL exceptions, including system exit signals (like Ctrl+C), which can make it hard to stop your program. Always specify the exception type or use except Exception:.