Python异常处理:常见的捕获和处理方式
在Python中,异常处理是一种机制,允许我们在程序运行时遇到错误时进行适当的处理。以下是几种常见的捕获和处理方式:
try/except:
try:
# 这里是可能会引发错误的代码
result = 10 / 0 # 这会引发除以零的错误
print(result)
except ZeroDivisionError: # 捕获特定类型的错误
print("Error: Division by zero is not allowed.")
finally:
try:
result = 10 / 0 # 这会引发错误
print(result)
except ZeroDivisionError:
pass # 不处理,直接跳过
finally:
print("This is always executed, regardless of errors or exceptions.")
assert:
def check_positive(x):
assert x > 0, f"Value {x} should be positive."
check_positive(-1) # 这会引发错误,因为-1不是正数
通过以上这些方式,我们可以在遇到错误时进行适当的处理,保证程序的稳定运行。
还没有评论,来说两句吧...