Master Python Exception Handling: try, except, else, and finally Explained
Master Python Exception Handling: try, except, else, and finally Explained
This guide walks you through Python’s exception handling constructs with practical code snippets and best‑practice tips.
Video: Python Exception Handling (try..except..finally)
Exceptions in Python
Python raises built‑in exceptions whenever a runtime error occurs. The interpreter halts the current block of code and propagates the exception up the call stack until a handler is found. If no handler exists, the program terminates and prints a traceback.
Consider the following call chain: A calls B, which calls C. If C raises an exception that isn’t handled locally, the exception bubbles up to B and then to A. Unhandled exceptions result in an abrupt program crash.
Catching Exceptions in Python
To intercept an exception, place the potentially unsafe code inside a try block. The except clause contains the logic that executes when an exception occurs.
Here’s a concise example that demonstrates the flow:
# Import the sys module to inspect the exception type
import sys
random_list = ['a', 0, 2]
for entry in random_list:
try:
print("The entry is", entry)
r = 1 / int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
Output
The entry is a Oops! <class 'ValueError'> occurred. Next entry. The entry is 0 Oops! <class 'ZeroDivisionError'> occurred. Next entry. The entry is 2 The reciprocal of 2 is 0.5
The code iterates over random_list. If the conversion to int or division fails, the except block handles the error, logs it, and moves to the next item. When a successful conversion occurs, the loop breaks and the reciprocal is printed.
Because all built‑in exceptions inherit from Exception, you can catch them generically:
# Import the sys module to inspect the exception type
import sys
random_list = ['a', 0, 2]
for entry in random_list:
try:
print("The entry is", entry)
r = 1 / int(entry)
break
except Exception as e:
print("Oops!", e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
The output is identical, but the handler now references the specific exception class via e.__class__.
Catching Specific Exceptions in Python
Broadly catching all exceptions can mask bugs and make debugging difficult. Instead, list only the exception types you expect.
A try block may contain multiple except clauses; only the first matching clause executes. Example:
try:
# code that may raise an error
pass
except ValueError:
# handle ValueError
pass
except (TypeError, ZeroDivisionError):
# handle either TypeError or ZeroDivisionError
pass
except Exception:
# fallback for any other exception
pass
Raising Exceptions in Python
Beyond automatic exceptions, developers can raise errors explicitly using the raise statement. Optionally, pass a message to clarify the reason.
raise KeyboardInterrupt
# Traceback: KeyboardInterrupt
raise MemoryError("This is an argument")
# Traceback: MemoryError: This is an argument
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
Python try with else Clause
The optional else clause runs only when the try block completes without raising an exception. This pattern keeps success‑path code separate from error handling.
Example: printing the reciprocal of an even number.
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1 / num
print(reciprocal)
Output when entering an odd number:
Enter a number: 1 Not an even number!
Output when entering an even number:
Enter a number: 4 0.25
Note that if num is zero, ZeroDivisionError is raised in the else block and is not caught by the preceding except clause.
Python try…finally
The finally clause guarantees that cleanup code runs regardless of whether an exception occurred. This is essential when working with external resources such as files, network connections, or GUIs.
Typical usage with file handling:
try:
f = open("test.txt", encoding='utf-8')
# perform file operations
finally:
f.close()
The file is always closed, even if an error arises during processing.
Python
- Python Statements, Indentation, and Comments: A Clear Guide
- Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
- Mastering Python If…Else Statements
- Mastering the Python Pass Statement: A Practical Guide
- Master Python Exception Handling: try, except, else, and finally Explained
- Build a Remote Temperature Sensor with Raspberry Pi and Python – Step‑by‑Step Guide
- Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained
- How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
- Master Python Exception Handling: Using try, except, finally, and raise Effectively
- Accessing Web Data with Python’s urllib: A Practical Guide