How to Handle Exceptions in Python (Try-Except-Finally)
Learn how to handle exceptions in Python using try, except, else, and finally blocks. Write error-free and crash-resistant Python code.
Explanation
Robust software must be prepared to handle unexpected conditions, such as missing files, invalid user inputs, database failures, or network disruptions. When an error occurs in Python, it raises an exception. If left unhandled, exceptions halt your program immediately and print a traceback stack.
Python's primary tool for managing runtime errors is the `try-except` block. You place code that might raise an error inside the `try` block, and define error-handling code inside one or more `except` blocks. Specifying the exact exception class (like `ValueError` or `ZeroDivisionError`) is highly recommended, as catching all exceptions generic (`except:`) can mask bugs.
To make your exception flow more expressive, Python provides two additional blocks: `else` and `finally`. The `else` block executes only if no exceptions were raised in the `try` block, which is useful for code that should only run on success. The `finally` block executes *always*, regardless of whether an exception occurred, making it the perfect place for cleanups like closing files or database connections.
Step-by-Step Implementation
- 1
Place code that could fail inside a try block.
- 2
Catch specific error types with except ExceptionType: blocks to handle failures gracefully.
- 3
Use else for code that must execute only on successful try blocks.
- 4
Utilize finally to guarantee cleanup actions run regardless of errors.
Code Example
This script demonstrates robust error handling in Python using try, except, else, and finally.
def divide_numbers(a, b):
try:
# Code that might raise an exception
result = a / b
except ZeroDivisionError:
# Handling a specific exception
print("Error: Cannot divide by zero!")
except TypeError:
# Handling another exception type
print("Error: Inputs must be numbers!")
else:
# Run only if try block succeeded
print(f"Success! Result of {a}/{b} is {result}")
finally:
# Runs no matter what
print("Division attempt completed.")
divide_numbers(10, 2)
print("---")
divide_numbers(10, 0)Success! Result of 10/2 is 5.0
Division attempt completed.
---
Error: Cannot divide by zero!
Division attempt completed.Frequently Asked Questions
Can I catch multiple exceptions in a single except block?
Yes, you can pass them as a tuple: except (ValueError, TypeError) as e:.
How do I raise my own exceptions?
Use the raise keyword followed by the exception instance: raise ValueError("Invalid configuration value").
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.