捕捉异常可以使用try/except语句。
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
try:
<语句> #运行代码
except:
发生异常,执行这块代码
except(Exception1[, Exception2[,...ExceptionN]]]):
发生以上多个异常中的一个,执行这块代码
except Exception as err:
print('error:',err) #输出错误原因
except ExceptionType, Argument:
你可以在这输出 Argument 的值... #如果引发了'name'异常,获得附加的数据
else:
<语句> 如果没有异常发生执行此处,
如果要使用else,就不要在try中使用return
finally:
<语句> 退出try时总会执行,
如文件关闭操作,保证文件能够关闭,
如果有finally,try中有return也会执行finally,
try中的return会被finally中的return值覆盖
raise Exception('')
触发异常后,后面的代码就不会再执行
def func():
a = int(input('a:'))
if a >= 10:
raise Exception('必须小于10')
else:
print('a=',a)
def func():
print('------------计算器--------------')
try:
a1 = int(input('num1:'))
a2 = int(input('num2:'))
per= input('+/')
result =0
if per == '+':
result = a1+a2
elif per == '/':
result = a1 / a2
print(result)
except ZeroDivisionError:
print('除数不为0')
except ValueError:
print('输入数字')
else:
print('成功结束')
finally:
print('---------------------------')
捕捉到的异常在except中从上往下匹配判断,如果先匹配到上级的except就执行这段代码,因此,包含异常最多的如exceptio放在最下面
def func():
print('------------计算器--------------')
try:
a1 = int(input('num1:'))
a2 = int(input('num2:'))
per= input('+/')
result =0
if per == '+':
result = a1+a2
elif per == '/':
result = a1 / a2
print(result)
with open('e:\p2\b.txt','r') as stm:
stm.read()
except Exception:
print('error')
except ZeroDivisionError:
print('除数不为0')
except ValueError:
print('输入数字')
except FileExistsError:
print('w')
except Exception as err: 输出错误原因
print('error:',err)
def func():
print('------------计算器--------------')
try:
a1 = int(input('num1:'))
a2 = int(input('num2:'))
per= input('+/')
result =0
if per == '+':
result = a1+a2
elif per == '/':
result = a1 / a2
print(result)
with open('e:\p2\b.txt','r') as stm:
stm.read()
except Exception as err:
print('error:',err)
def func():
try:
with open(r'e:\py_projects\a1.txt','rb') as stm:
con = stm.read()
return con
except Exception as err:
print('error:',err)
finally:
return 3
print(func())#3
因篇幅问题不能全部显示,请点此查看更多更全内容