Syntax
try:\n # risky code\nexcept ExceptionType as e:\n # handle itExamples
Basic Exception Handling
Catching an error instead of letting the program crash.
try:
number = int("not a number")
except ValueError:
print("That wasn't a valid number")
print("Program continues running")Catching Specific Exceptions
Handling different error types differently by listing multiple except blocks.
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Both arguments must be numbers")
divide(10, 0) # Cannot divide by zero
divide(10, "two") # Both arguments must be numbersUsing finally
Running cleanup code that always executes, whether or not an exception occurred.
def read_config():
try:
print("Reading configuration...")
raise FileNotFoundError("config.json missing")
except FileNotFoundError as e:
print(f"Error: {e}")
finally:
print("Cleanup complete") # always runs
read_config()Raising Custom Exceptions
Intentionally raising an exception to signal an invalid state.
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient funds")
return balance - amount
try:
new_balance = withdraw(100, 150)
except ValueError as e:
print(f"Transaction failed: {e}")Best practices
- Catch specific exception types (ValueError, KeyError, etc.) rather than a bare except:, which can silently swallow unrelated bugs
- Use finally for cleanup code (closing files, releasing resources) that must run regardless of success or failure
- Raise exceptions with clear, descriptive messages to make debugging easier for whoever encounters the error
- Don't use try/except for normal control flow when a simple if check would do - exceptions are for genuinely exceptional situations
- Consider using the else clause on try blocks for code that should only run if no exception was raised
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
The if statement is Python's primary conditional control structure. It allows your program to make decisions by executing different code blocks based on whether a condition is True or False. The if statement is fundamental to creating dynamic, responsive programs that can adapt their behavior based on various conditions, user input, or data states.for
The for loop in Python is used to iterate over sequences like lists, tuples, strings, or any iterable object. Unlike traditional for loops in other languages that use counters, Python's for loop is more like a "for each" loop, automatically handling the iteration details. It's one of the most commonly used constructs in Python for processing collections and repeating actions.while
The while loop repeats a block of code as long as its condition remains True. Unlike a for loop, which iterates a known number of times over a sequence, a while loop is ideal when you don't know in advance how many iterations you'll need - like waiting for valid user input or running until some external condition changes. A while loop can also have an optional else clause that runs if the loop finishes normally, without hitting a break.break and continue
break and continue give you fine-grained control over loop execution. break immediately exits the nearest enclosing loop entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the next one, without exiting the loop. Both work inside for and while loops.