![](https://img.haomeiwen.com/i4914634/bb8388257717de9c.png)
The core values of Chinese socialism
异常
- 广义上的错误分为错误和异常
- 错误指的是可以人为避免的
- 异常是指在语法和逻辑正确的前提下,出现的问题
- 在Python里,异常是一个类,可以处理和使用
异常处理
# 简单异常案例
try:
num = int(input("Plz input your number:"))
rst = 100/num
print("result = {}".format(rst))
except:
print("你TM输的啥玩意!!!")
#exit()退出程序
exit()
Plz input your number:0
你TM输的啥玩意!!!
ERROR:root:Invalid alias: The name clear can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name more can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name man can't be aliased because it is another magic command.
# 简单异常案例
#给出提示信息
try:
num = int(input("Plz input your number:"))
rst = 100/num
print("result = {}".format(rst))
# 捕获异常后,把异常实例化,出错信息在实例化里
# 注意以下写法
# 以下语句是捕获ZeroDivisionError异常并实例化实例e
# 在异常类继承关系中,越是子类的异常,越要往前放,越是父类的异常,越要往后放
# 在处理异常的时候,一旦拦截到某一个异常,则不再继续往下查看except,有finally则执行finally语句块,否则就执行下一个大语句
except ZeroDivisionError as e:
print("你TM输的啥玩意!!!")
print(e)
exit()
except NameError as e:
print("名字起错了")
print(e)
exit()
except AttributeError as e:
print("属性有问题")
print(e)
exit()
# 所有异常都是继承自Exception,任何异常都会拦截
# 而且一定是最后一个except
except Exception as e:
print("不知道什么错!")
print(e)
exit()
finally:
print("我肯定会被执行的")
Plz input your number:0
你TM输的啥玩意!!!
division by zero
我肯定会被执行的
ERROR:root:Invalid alias: The name clear can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name more can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.
ERROR:root:Invalid alias: The name man can't be aliased because it is another magic command.
网友评论