Goal: Learn to handle errors and make programs reliable.
Why Programs Crash
number = 10 / 0 # ZeroDivisionError: division by zero
Solution: try/except โ catch the error and handle it gracefully.
Basic Syntax
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Using a bare except: (without a type) is bad practice โ it hides real problems.
Common Error Types
# ValueError โ invalid value
try:
age = int("twenty")
except ValueError:
print("Please enter a number!")
# FileNotFoundError โ file not found
try:
with open("missing.txt") as f:
data = f.read()
except FileNotFoundError:
print("File not found!")
# KeyError โ key missing from dict
try:
age = user["age"]
except KeyError:
print("Key 'age' is missing!")
# TypeError โ incompatible types
try:
result = "5" + 10
except TypeError:
print("Incompatible types!")
# IndexError โ index out of range
try:
print([1, 2, 3][10])
except IndexError:
print("Index out of range!")
Multiple except + Error Details
try:
age = int(input("Age: "))
result = 100 / age
except ValueError:
print("Please enter a number!")
except ZeroDivisionError:
print("Age cannot be zero!")
except Exception as e: # catch everything else
print(f"Unexpected error: {e}")
finally and else
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
else:
process(data) # runs only on success
finally:
print("Always runs") # cleanup
When NOT to Use try/except
# โ Bad โ hiding bugs
try:
hacky_code()
except:
pass
# โ Bad โ replacing checks
try:
if user["age"] > 18: ...
except KeyError:
...
# โ
Good โ check first
if "age" in user and user["age"] > 18: ...
When to Use try/except
# User input
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a whole number.")
# Files
try:
with open("config.json") as f:
config = json.load(f)
except FileNotFoundError:
config = {}
# Network / API
try:
response = requests.get(url, timeout=5)
except (ConnectionError, TimeoutError):
print("Server unavailable")
Best Practices
| โ Do | โ Don’t |
|---|---|
| Catch specific exceptions | Bare except: without type |
Narrow try block (only risky code) |
Entire code in one try |
| Give clear error messages | except: pass |
Use finally for cleanup |
Use try/except instead of checks |
Golden rule: Use try/except where you can’t predict the outcome โ user input, files, network.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!