在Python中处理异常,有效防止程序崩溃
在Python中,处理异常是通过使用try/except语句实现的。以下是一个基本的例子:
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("Can't divide by zero!")
return None
result = divide(10, 2)
if result is not None:
print(f"The quotient is {result}")
在这个例子中,我们尝试除以零。当发生这种错误时,程序会跳到except子句,并执行其后的代码。
通过这种方式,我们可以在Python程序中处理各种可能发生的异常,从而确保程序的稳定性和可靠性。
还没有评论,来说两句吧...