Python 常用 try ... except...finally
处理异常:
try:
funct()
except Exception as e:
handle_error()
finally:
continue_process()
把可能出错的代码放入 try
,一旦出现异常就停止执行,转到 except
,异常处理的步骤放在 except
内,finally
中的代码在处理完异常后会继续执行
⛅举个例子:
try:
a = 1
b = 2 / 0 # 报错,停止执行抛出异常
c = 3 # 由于上一行报错,所以这行未执行
except Exception as e:
print(e) # division by zero
finally:
# 继续执行
print(a) # 1
print(c) # name 'b' is not defined
2. 自定义抛出异常
⛅除了让程序自动抛出异常,也可以自己指定抛出异常,语法为:
raise Exception(message)
举个例子:
def divide(a, b):
if b == 0:
raise Exception('Divided by zero!!!')
else:
return a / b
try:
a = 1
b = 0
print(f'{a} / {b} = {divide(a, b)}')
except Exception as e:
print(e)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)