Catch and handle exceptions with try / except / else / finally
Distinguish between common exception types
Raise exceptions intentionally with raise
Create custom exception classes
⚡ Exception Explorer
Click an exception type to see what causes it, the error message, and how to handle it properly.
Exceptions vs Syntax Errors
Python has two kinds of errors. Syntax errors are caught before the program runs (wrong indentation, missing colon). Exceptions happen at runtime — the code is syntactically valid but something goes wrong during execution (dividing by zero, missing file, wrong type).
try / except / else / finally
try — code that might raise an exception
except ExceptionType as e — runs if that exception is raised; e holds the exception object
else — runs only if NO exception was raised in try
finally — always runs, whether or not an exception occurred (great for cleanup)
Custom Exceptions
You can define your own exception classes by inheriting from Exception. This lets callers catch your specific error type and provides more meaningful error messages.
raise ValueError("Age must be positive") — raise built-in or custom exceptions to signal invalid states.
Quick Check
1. When does the else block in a try/except run?
When an exception is raised
When no exception is raised in the try block
Always, regardless of whether an exception occurred
Only when the except block doesn't match the exception type
2. Which exception is raised by int("hello")?
TypeError
ValueError
AttributeError
IndexError
3. What is the purpose of the finally block?
It runs only if an exception was caught
It always runs — used for cleanup like closing files or network connections