Python错误处理:异常捕获示例
在Python中,异常是程序运行过程中遇到的不能正常执行的情况。我们可以使用try/except块来捕获和处理这些异常。
下面是一个基本的异常捕获示例:
def divide_by_zero():
try:
result = 10 / 0
print("This should raise a ZeroDivisionError.")
print(f"Result: {result}")
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This block is executed regardless of the exception.")
divide_by_zero()
在这个示例中,我们尝试进行一个除以零的操作。这会导致ZeroDivisionError
异常。
我们使用try/except块来捕获这个异常,并在捕获到异常时执行特定的代码(这里打印错误信息)。
无论是否发生异常,finally块中的代码都会被执行。
还没有评论,来说两句吧...