try / except / else / finally
Python handles exceptions using the try/except syntax. Use it when you want to continue execution after an error, or branch behavior based on the type of error. Avoid silently swallowing exceptions (an empty except block) as it makes bugs difficult to find. The else block runs when no exception occurs; the finally block always runs regardless of whether an exception was raised.
Syntax
try:
# Code that may raise an exception
except ExceptionClass as e:
# Handle the exception
except (ExceptionClass1, ExceptionClass2) as e:
# Handle multiple exception types at once
else:
# Runs if no exception was raised
finally:
# Always runs, with or without an exception
# Raise an exception manually
raise ExceptionClass("message")
Keyword Reference
| Keyword | Description |
|---|---|
| try | Wraps code that may raise an exception. |
| except ExceptionClass | Runs when the specified exception type is raised. |
| except Exception as e | Captures the exception object in variable e. |
| else | Runs if the try block completed without raising an exception. |
| finally | Always runs regardless of whether an exception occurred (used for cleanup). |
| raise | Raises an exception intentionally. |
| Exception | The base class for standard exceptions. |
Sample Code
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}") # Error: division by zero
# Handling multiple exceptions
def convert_to_int(value):
try:
return int(value)
except ValueError:
print(f"'{value}' cannot be converted to an integer")
return None
except TypeError:
print(f"Invalid type: {type(value).__name__}")
return None
print(convert_to_int('42')) # 42
print(convert_to_int('abc')) # Error message + None
print(convert_to_int(None)) # Error message + None
# else: runs when no exception is raised
try:
num = int(input("Enter a number: "))
except ValueError:
print("That is not a number")
else:
print(f"You entered: {num}") # Only runs if no exception occurred
# finally: always runs (e.g., for releasing resources)
file = None
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
if file:
file.close() # Close the file regardless of whether an exception occurred
# raise: raise an exception intentionally
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
print(divide(10, 0))
except ValueError as e:
print(f"Error: {e}") # Error: Cannot divide by zero
# Re-raising an exception
try:
result = divide(10, 0)
except ValueError:
print("Logged the error")
raise # Re-raise the same exception
Notes
except clauses are evaluated from top to bottom, so place more specific exception classes before more general ones. For example, Exception is the base class for nearly all exceptions — if placed first, the except blocks below it will never be reached.
The else block is useful for code that should only run when the try block succeeds but does not belong inside the try block itself. This keeps error-handling code clearly separated from the success path.
For managing resources such as files or network connections, using a with statement (context manager) is more Pythonic than relying on finally. A with block automatically releases the resource when the block exits.
If you find any errors or copyright issues, please contact us.