zoukankan      html  css  js  c++  java
  • 第十九篇 异常

    一、为什么要用异常

    在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!!

    常用异常:

     1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
     2 IOError 输入/输出异常;基本上是无法打开文件
     3 ImportError 无法引入模块或包;基本上是路径问题或名称错误
     4 IndentationError 语法错误(的子类) ;代码没有正确对齐
     5 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
     6 KeyError 试图访问字典里不存在的键
     7 KeyboardInterrupt Ctrl+C被按下
     8 NameError 使用一个还未被赋予对象的变量
     9 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    10 TypeError 传入对象类型与要求的不符合
    11 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    12 导致你以为正在访问它
    13 ValueError 传入一个调用者不期望的值,即使值的类型是正确的

    二、捕捉异常方式

    优先不做第一个异常进行操作,如果没有捕捉到,后续继续捕捉

    1 try :
    2    #内容   
    3 except IndexError as e:
    4 print()
    5 except Exception as e
    6  

    三、异常结构

    1)如果有错误执行try,之后执行finally。如果执行没有错误,执行else,执行finally

    try:
       #主代码块
    except keError as e:
      #异常时,执行该块
      pass
    except IndexError as e:
      pass
    except Exception as e:
     pass
    else#主代码快执行完,执行该块
       pass
    finally#无论异常与否,最终执行该块
       pass

    2)主动触发异常

    1 try:
    2    raise Exception(“出错了”)
    3 except Exception as e:
    4    print e

    3)自定义异常

    class  pyrene(Exception):
       def __init__(self,msn):
           self.a = msn
       def __str__(self):
           return self.a
    try:
       raise pyrene(“错误了。。”)
    exception  pyrene as e:
    print e

    4)万能异常

    Exception:万能异常捕获,所有的错误都是Exception的基类,并且Exception方法内部就有__str__这个方法

    1 try:
    2   #内容
    3 except Exception as e
    4    print e

     

    4)断言

    断言就是异常的简写方式:

    assert 后面是需要判断的条件,如果条件正确就ok。如果条件出错,那么就报异常

    # assert 条件

    assert 1 == 1

     

    assert 1 == 2

     

    下面是自定义异常案例代码

    try:
        print("123")
        raise Exception("出错了")
    except Exception as e:
        #封装了错误信息的对象
        print(e)
    #Exception就有类似下面的方法
    class Foo:
        def __init__(self,args):
            self.xo = args
        def __str__(self):
            return self.xo
    obj = Foo("出错了")
    print(obj)
    View Code
  • 相关阅读:
    将vue文件script代码抽取到单独的js文件
    git pull 提示错误:Your local changes to the following files would be overwritten by merge
    vue和uniapp 配置项目基础路径
    XAMPP Access forbidden! Access to the requested directory is only available from the local network.
    postman与newman集成
    postman生成代码段
    Curl命令
    POST方法的Content-type类型
    Selenium Grid 并行的Web测试
    pytorch转ONNX以及TnesorRT的坑
  • 原文地址:https://www.cnblogs.com/pyrene/p/6414715.html
Copyright © 2011-2022 走看看