zoukankan      html  css  js  c++  java
  • 异常处理

    异常处理,虽然程序出错了,但是可以做一些预处理,使得程序不崩溃

    data = {'name':'ABCD',
            'age':22}
    aa = [1,2,3,4]
    try:
        data['naaa']
        aa[5]
    
    # except (KeyError,IndexError) as e:
    #     print()   #当出现错误后处理方法一样,可以用这种方法
    #------分别抓取错误----
    # except KeyError as e:
    #     print("the key is error",e)
    # except IndexError as e:
    #     print("the index ",e)
    except Exception as e:
        print("出错了",e)    # 能基本抓住所有错误,常用第二种方法

    其他方式

    data = {'name':'ABCD',
            'age':22}
    aa = [1,2,3,4]
    try:
        # data['naaa']
        aa[2]
    
    except KeyError as e:
        print("the key is error",e)
    except IndexError as e:
        print("the index ",e)
    except Exception as e:
        print("未知错误",e)
    else:
        print("else,如果没有错,执行")
    finally:
        print("finally不管有没有错,都执行")
    
    # else,如果没有错,执行
    # finally不管有没有错,都执行

    自己写的异常

    class ABCException(Exception):
        def __init__(self,msg):
            self.msg = msg
    
        def __str__(self):   # __str__ 可以自定义,也可以不写使用基类的
            return self.msg
    
    try:
        raise ABCException("自己写的异常")    #自己写的异常需要自己触发
    except ABCException as e:
        print(e)
  • 相关阅读:
    c# 解决读取Excel混合文本类型,数据读取失败的解决方法
    c#中的常用ToString()方法总结
    vsts
    RSA加密解密
    odbc连接数据库
    SerialPort
    C# Winform下载文件并显示进度条
    c# 面试题
    SQL Server 存储过程
    mysql 事务处理
  • 原文地址:https://www.cnblogs.com/yfjly/p/9866229.html
Copyright © 2011-2022 走看看