Python Docs
Python Try "Except" — Core Cheat Sheet
What is Exception Handling?
Exception handling prevents your program from crashing when something goes wrong. Python uses the try–except structure to catch and handle errors safely.
Purpose of Try–Except
- try — Code that may cause an error
- except — Runs when an error occurs
Basic Try–Except
If an error happens in try, the except block handles it.
try:
print(x)
except:
print("An exception occurred")Without Try–Except (Program Crashes)
Without exception handling, Python stops the program immediately.
print(x) # Causes error because x is not definedCatching Specific Exceptions
You can catch specific errors like NameError, ValueError, or TypeError. This helps you customize responses for different error types.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")Common Exceptions You Can Catch
| Exception Type | Meaning |
|---|---|
| NameError | Variable not defined |
| ValueError | Wrong value used |
| TypeError | Wrong data type used |
| ZeroDivisionError | Division by zero |
| FileNotFoundError | File does not exist |
| KeyError | Missing dictionary key |
| IndexError | List index out of range |
Summary
- try runs risky code
- except catches the errors
- Use specific exceptions for debugging
- Prevents program crashes