Python高级-异常处理

The core values of Chinese socialism

异常

  • 广义上的错误分为错误和异常
    • 错误指的是可以人为避免的
    • 异常是指在语法和逻辑正确的前提下,出现的问题
    • 在Python里,异常是一个类,可以处理和使用

异常处理

  • 不能保证程序永远正确运行
  • 必须保证程序在最坏的情况下得到的问题被妥善处理
  • Python的异常处理模块全部语法:
    try:
        尝试实现某个操作,
        如果没出现异常,任务就可以完成
        如果出现异常,将异常从当前代码块扔出去尝试解决异常
    
    except 异常类型1:
        解决方案1:用于尝试在此处处理异常解决问题
    except 异常类型2:
        解决方案3:用于尝试在此处处理异常解决问题
    
    except (异常类型3, 异常类型4):
        解决方案:针对多个异常使用相同的处理方式
    
    except :
        解决方案:所有异常的解决方案
        
    else:
        如果没有出现异常,将会执行此处代码
        
    finally:
        管你有没有错误都要执行的代码
        
    
# 简单异常案例
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.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容