1.try-except
try:
a = int(input('请输入第一个数:'))
b = int(input('请输入第二个数:'))
result = a/b
print('结果为:',result)
except ZeroDivisionError:
print('除数不能为0')
except ValueError:
print('只能输入数字')
# except后也可以什么都不写
2.try-except-else
try:
a = int(input('请输入第一个数:'))
b = int(input('请输入第二个数:'))
except BaseException as e: # BaseException意思是出错,as e 是给前面的起个别名e
print('出错了', e)
else: # 不报错执行else
result = a/b
print('结果为:', result) # 该代码会报除数为0的错误,因为a/b在except之下
3.try-except-else-finally
try:
a = int(input('请输入第一个数:'))
b = int(input('请输入第二个数:'))
except BaseException as e: # BaseException意思是出错,as e 是给前面的起个别名e
print('出错了', e)
else: # 不报错执行else
result = a/b
print('结果为:', result) # 该代码会报除数为0的错误,因为a/b在except之下
finally: # 无论是否出错都会执行
print('谢谢!')
4.常见的异常类型
5.traceback打印错误信息
import traceback # 导入traceback模块
try:
a = int(input('请输入第一个数:'))
b = int(input('请输入第二个数:'))
result = a/b
except:
traceback.print_exc()
else:
print('结果为:', result)
finally:
print('谢谢!')