heaven123

python 异常处理

def count_word(filename):
try:
with open(filename,encoding='utf-8') as file:
centent=file.read()
except FileNotFoundError:
print('filename '+filename+ ' does not exist')
else:
new_words=centent.split()
print(filename+" has about "+str(len(new_words))+' words')
count_word('python_study')


def division():
while True:
try:
num1=int(input('请输入数字:'))
num2=int(input('请输入数字:'))
res=num1/num2
except ValueError as ve:
print('请输入数字!')
print(ve)
except ZeroDivisionError as ze:
print('除数不能为零')
print(ze)
else:
return res
finally:
print('test')#不论是否异常都会执行
print(division())

def division():
while True:
try:
num1=int(input('请输入数字:'))
num2=int(input('请输入数字:'))
res=num1/num2
except Exception as e:#所有异常都可以捕捉到
print(e)
else:
return res
finally:
print('test')#不论是否异常都会执行
print(division())



posted on 2019-07-23 18:55  heaven123  阅读(178)  评论(0编辑  收藏  举报

导航