第一种:try except 抛出异常结束程序运行
def collatz(number):
try:
number = int(number)
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
except ValueError:
return '类型错误'
for i in range(1,7):
num = input()
print(collatz(num))
print('你已经输入了{0}次,还剩{1}次!'.format(i,7-i))
第二中:try except finally 抛出异常后继续执行
def collatz(number):
try:
number = int(number)
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
except ValueError:
global re
re = '类型错误'
print(re)
return ''
finally:
print('我是在抛出{0}异常后,继续运行的程序块!'.format(re))
for i in range(1,7):
num = input()
print(collatz(num))
print('你已经输入了{0}次,还剩{1}次!'.format(i,7-i))
其中except 后面的错误类型,可以根据具体要抛出错误类型需求修改,我们这里取了ValueError