• python 异常处理, 打印系统报错原文,断言assert


    1. 什么是异常处理
    异常是错误发生的信号,一旦程序出错就会产生一个异常,如果该异常
    没有被应用程序处理,那么该异常就会抛出来,程序的执行也随之终止

    异常包含三个部分:
      1. traceback异常的追踪信息
      2. 异常的类型
      3. 异常的信息

    错误分为两大类:
      1. 语法上的错误:在程序运行前就应该立即修正
      2. 逻辑上的错误

    2. 为何要异常处理

    避免程序因为异常而崩溃,所以在应用程序中应该对异常进行处理,从而增强程序的健壮性

    try:
        代码1
        代码2
        代码3
        ......
    except NameError:
        当抛出的异常是NameError时执行的子代码块
    except ....:
        pass
    except ...:
        pass
    else:
        pass
    finally:
        pass
    1.常见的逻辑错误导致的异常
    print('adsfsadf'
    
    age=input('>>: ').strip()
    print(age > 10) #TypeError
    
    for i in 10: #TypeError
        pass
    
    import os
    os.xxx #AttributeError
    
    1 / 0 #ZeroDivisionError:
    
    print('=====1')
    print('=====2')
    print('=====3')
    l=[1,2,3]
    l[1000] #IndexError
    print('=====4')
    d={'x':1,'y':2}
    d['z'] #KeyError
    print('=====5')
    2. 异常处理
    # 异常处理的单分支
    try:
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        d['z']  # KeyError
        print('=====4')
        l = [1, 2, 3]
        l[1000]  # IndexError
        print('=====5')
    except IndexError:
        print('IndexError')
    
    print('other code')
    
    # 异常处理的多分支
    try:
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        d['z']  # KeyError
        print('=====4')
        l = [1, 2, 3]
        l[1000]  # IndexError
        print('=====5')
    except KeyError as e:
        print('KeyError',e)
    except IndexError as e:
        print('IndexError',e)
    
    
    print('other code')
    
    
    
    
    try:
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        # d['z']  # KeyError
        print('=====4')
        l = [1, 2, 3]
        l[1000]  # IndexError
        print('=====5')
    except (KeyError,IndexError) as e:
        print(e)
    print('other code')
    
    # 万能异常类型Exception:可以匹配任意类型的异常
    try:
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        # d['z']  # KeyError
        # xxx
        print('=====4')
        l = [1, 2, 3]
        l[1000]  # IndexError
        print('=====5')
    except IndexError as e:
        print('IndexError:', e)
    except KeyError as e:
        print('KeyError:', e)
    except Exception as e:
        print('Exception:',e)
    
    print('other code')
    
    # try... else...
    try:
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        # d['z']  # KeyError
        # xxx
        print('=====4')
        l = [1, 2, 3]
        # l[1000]  # IndexError
        print('=====5')
    except IndexError as e:
        print('IndexError:', e)
    except KeyError as e:
        print('KeyError:', e)
    except Exception as e:
        print('Exception:',e)
    else:
        print('else必须放到后面,else的子代码块会在被检测的代码没有异常的情况下执行')
    # print('other code')
    
    # try... finally...
    try:
        f=open('a.txt','w')
        print('=====1')
        print('=====2')
        print('=====3')
        d = {'x': 1, 'y': 2}
        # d['z']  # KeyError
        # xxx
        'xx' > 10
        print('=====4')
        l = [1, 2, 3]
        # l[1000]  # IndexError
        print('=====5')
    
    except IndexError as e:
        print('IndexError:', e)
    except KeyError as e:
        print('KeyError:', e)
    # except Exception as e:
    #     print('Exception:',e)
    else:
        print('else必须放到后面,else的子代码块会在被检测的代码没有异常的情况下执行')
    finally:
        print('无论被检测的代码有没有异常都会执行')
        f.close()
    
    
    # 主动触发异常
    print('===>1')
    print('===>2')
    raise TypeError('类型错误')
    print('===>3')
    
    class People:
        def __init__(self,name,age):
            self.__name=name
            self.__age=age
    
        def tell_info(self):
            print(self.__name,self.__age)
    
        def set_info(self,name,age):
            if not isinstance(name,str):
                raise TypeError('名字必须是str类型')
            if not isinstance(age,int):
                raise TypeError('年龄必须是int类型')
            self.__name=name
            self.__age=age
    
    obj=People('egon',18)
    # print(obj.__dict__)
    # obj.tell_info()
    
    obj.set_info('egon',123)
    obj.tell_info()
    #
    
    
    # 自定义异常类型(了解)
    class MyException(BaseException):
        def __init__(self,msg):
            super().__init__()
            self.msg=msg
    
        def __str__(self):
            return '<%s>' %self.msg
    
    raise MyException('我自定义的异常')

    打印系统报错原文 

    import traceback
    
    def test():
        try:
            int('dsadsa')
        except Exception as e:
            print(traceback.format_exc())   # 打印系统报错原文
    
        print('hello')
    
    test()
    
    '''
    Traceback (most recent call last):
      File "D:/oldboy_edu/python_code/day100/py13client/test/s2.py", line 35, in test
        int('dsfsf')
    ValueError: invalid literal for int() with base 10: 'dsfsf'
    
    hello
    '''

     断言

    格式:

    assert 条件,断言失败的自定义信息

    断言条件通过,代码进行网下,断言条件失败,直接抛出异常(异常信息可以自定义)

    a = 2
    assert (a>1)
    print('断言成功,程序继续向下执行')
    
    b = 2
    assert (b>=3),'b小于3'    # 报错 AssertionError: b小于3
    print('断言失败,程序报错')
  • 相关阅读:
    LeetCode数字之和总结
    排序类总结
    web sockect的练习
    RNA速率scVelo
    创建Numpy数组的不同方式
    numpy的课程学习二
    scrapy的cmdline命令和其文件写入乱码问题
    scrapy选择器
    python数据分析的numpy学习笔记
    Numpy的学习笔记一
  • 原文地址:https://www.cnblogs.com/ludingchao/p/12096181.html
Copyright © 2020-2023  润新知