Comprehensive Guide to Python Exception Handling
This article explains Python exception handling fundamentals, covering basic try‑except, multiple exception catches, else/finally blocks, custom exceptions, exception propagation, raise‑from chaining, context manager handling, assert statements, generic suppression, and selective suppression with contextlib.
01 Basic Exception Throw and Catch
try:
# Attempt code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code executed when ZeroDivisionError is caught
print("除数不能为0")02 Multiple Exception Captures
try:
x = int(input("请输入一个数字: "))
y = int(input("请输入另一个数字: "))
result = x / y
except ValueError:
print("输入的不是有效的数字")
except ZeroDivisionError:
print("除数不能为0")03 Using else and finally
try:
f = open("myfile.txt")
# File operations...
except FileNotFoundError:
print("文件未找到")
else: # Executed if no exception occurs
print("文件处理完成")
finally: # Executed regardless of exception
f.close()04 Custom Exceptions
class MyException(Exception):
pass
def some_function():
raise MyException("这是一个自定义异常")
try:
some_function()
except MyException as e:
print(e)05 Exception Propagation: Throw Inside Function, Catch Outside
def divide(x, y):
if y == 0:
raise ZeroDivisionError("除数不能为0")
return x / y
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(e)06 Using raise ... from ... to Specify Exception Cause
def outer():
try:
inner()
except Exception as e:
raise ValueError("外层错误") from e
def inner():
raise KeyError("内层错误")
try:
outer()
except ValueError as e:
print(e) # Prints exception chain information07 Exceptions in Context Managers
with open("nonexistent_file.txt") as f:
content = f.read()
# If the file does not exist, IOError is automatically caught and the file is closed08 Using assert for Condition Checks
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price'], "无效的折扣"
return price
product = {'name': 'Widget', 'price': 100}
try:
print(apply_discount(product, 1.5)) # Discount > 1 triggers assert
except AssertionError as e:
print(e)09 Exception Suppression (Not Recommended)
try:
# Code that may raise an exception
...
except:
pass # Silently ignore all exceptions (discouraged)10 Selectively Ignoring Specific Exceptions with contextlib.suppress
from contextlib import suppress
with suppress(FileNotFoundError):
with open("missing_file.txt") as f:
read_data(f)
# No exception is raised if the file does not existSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
