Python高级-异常处理

2019-07-18  本文已影响0人  Yuanshuo
The core values of Chinese socialism

异常

异常处理

# 简单异常案例
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.
上一篇 下一篇

猜你喜欢

热点阅读