Exception Handling: try, except, else, finally
Unforeseen errors happen: a missing file, a database disconnection, or bad user input. Exception handling prevents crashes.
What is it?
The `try...except...else...finally` block allows Python programs to catch runtime errors (exceptions) and respond gracefully.
Why is it used?
Keeps backend servers running during errors and gives clean, actionable feedback to users.
Detailed Explanation
The 4 Blocks:
• `try`: Code that might raise an exception.
• `except SpecificError as e`: Handles the specific error.
• `else`: Runs only if NO exception occurred in the `try` block.
• `finally`: Runs unconditionally regardless of success or error (used for closing connections).
• Raising exceptions: `raise ValueError("Custom error message")`.
Syntax Structure
Syntax Blueprint
try:
# Risky code
except ValueError as e:
# Handle error
else:
# Success
finally:
# Cleanup
Code Example
PYTHON Code
# Safe Numeric Input & Division Handler
def safe_discount_calculator(price_str, discount_str):
try:
price = float(price_str)
discount = float(discount_str)
if price < 0 or discount < 0:
raise ValueError("Prices and discounts must be non-negative.")
discount_amount = price * (discount / 100)
final_price = price - discount_amount
except ValueError as err:
print(f"[ERROR] Invalid input value: {err}")
return None
except ZeroDivisionError:
print("[ERROR] Division by zero encountered.")
return None
else:
print(f"[SUCCESS] Final Price: ₹{final_price:.2f}")
return final_price
finally:
print("Calculation audit finished.\n")
safe_discount_calculator("2500", "10")
safe_discount_calculator("two-thousand", "10") # Catches parsing error
Explanation of the Code
• Catches `ValueError` when non-numeric text is parsed.
• Demonstrates manual `raise ValueError()` for business rules.
• Runs `else` on success and `finally` for closing logs.
Expected Output
[SUCCESS] Final Price: ₹2250.00
Calculation audit finished.
[ERROR] Invalid input value: could not convert string to float: 'two-thousand'
Calculation audit finished.
Real-World Application
Used across Flask and Django backends to handle 400 Bad Request and 500 Internal Server errors gracefully.
Common Mistakes to Avoid
• Catching bare `except:` without specifying the error type (swallows keyboard interrupts `Ctrl+C` and system exits!). Always catch specific errors (`except ValueError:`) or `except Exception:`.
• Putting too much unrelated code inside the `try` block.
Quick Practice Challenge
Write a `try...except` block catching a `FileNotFoundError` when trying to open a non-existent file.
Key Takeaways
• Catch specific exceptions (`ValueError`, `FileNotFoundError`).
• Use `else` for code that should only run if no error occurred.
• The `finally` block always executes for resource cleanup.