try / except
Overview
Exception handling prevents your program from catastrophically crashing when unexpected events occur (like network timeouts or malformed user input). You wrap risky code in a try block, catch specific errors with except, run cleanup code in finally, and execute success-only logic in else. This structure ensures your application can recover gracefully and continue operating.
Syntax
try:
num = int(input("Enter a denominator: "))
result = 100 / num
except ValueError:
print("Error: You didn't enter a valid integer.")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except Exception as e:
# Catches any other unforeseen errors
print(f"An unexpected error occurred: {e}")
else:
# Executes ONLY if the try block succeeds with no errors
print(f"Success! Result is {result}")
finally:
# Guaranteed to execute, even if a crash occurs or a return statement is hit
print("Execution complete. Cleaning up resources.")Common Pitfalls
- Using a 'bare except' (
except:). This is highly dangerous because it catches EVERYTHING, including SystemExit and KeyboardInterrupt (Ctrl+C). If your program enters an infinite loop, you literally cannot stop it. Always catchExceptioninstead. - Placing massive blocks of code inside the
tryblock. This makes it impossible to know exactly which line triggered the exception.
Interview Questions
else block in exception handling?The else block executes only if the try block succeeds. It is designed to keep the try block absolutely minimal, ensuring you only catch errors from the specific line you intended to wrap, rather than accidentally catching errors from subsequent success logic.
Real-World Example
Safely parsing JSON payloads received from untrusted APIs.
import json
json_payload = "{malformed_json_here}"
try:
data = json.loads(json_payload)
except json.JSONDecodeError:
print("API returned invalid JSON. Falling back to default.")
data = {"status": "error"} # Safe fallbackCheck Your Knowledge
Test your understanding of try / except with these quick questions.