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

    #1
    name=['a','s']
    try:
        print(name[3])
    except:
        print('list index out of range')#list index out of range
    #2
    data={}
    try:
        data['name']
    except KeyError as e:
        print('没有这个key:',e)#没有这个key 'name'
    #3
    name=['a','s']
    data={}
    try:
        print(name[3])#出错
        data['name']#上句出错,本句不会运行
    except (IndexError,KeyError) as e:
        print('出错:',e)#列表操作错误: list index out of range
    #4不建议用
    name=['a','s']
    data={}
    try:
        print(name[3])
        data['name']
    except Exception as e:#抓住所有的错误
        print('出错:',e)
    #5
    name=['a','s']
    data={}
    try:
        print(name[3])
        data['name']
    except IndexError as e:
        print('列表操作错误:',e)
    except KeyError as e:
        print('没有这个key:',e)#不会运行的
    #6 未知错误
    name=['a','s']
    data={}
    try:
        open('q.text')
    except (IndexError,SyntaxError) as e:
        print('出错:', e)
    except KeyError as e:
        print('没有这个key:',e)
    except Exception as e:
        print('未知错误',e)
    #一切正常
    name=['a','s']
    try:
        print(name[3])
    except IndexError as e:
        print('列表操作错误:',e)
    else:
        print('一切正常')
    #不管是否有错,都会执行
    data={}
    try:
        print(data['q'])
    except Exception as e:
        print('错误:',e)
    else:
        print('一切正常')
    finally:
        print('不管是否有错,都会执行')
    
    '''
    常用异常:
    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    注:缩进引起的错误,是无法被抓到的
    '''
    #自定义异常
    class qiqiException(Exception):
        def __init__(self, msg):
            self.message = msg
        # def __str__(self):#让类返回str格式
        #     return self.message
    try:
        raise qiqiException('我的异常情况呀')#raise触发异常
    except qiqiException as e:
        print(e)#结果:我的异常情况呀
    

      

  • 相关阅读:
    Ajax实现异步上传图片
    python文章的抓取
    python
    Python的MySQLdb模块安装
    import _mysql----ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。
    安装第三方模块时遇到Python version 2.7 required, which was not found
    beautifulSoup安装
    安装setuptools和pip
    python 的简单抓取图片
    python
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/8675064.html
Copyright © 2011-2022 走看看