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

    python2.x捕获异常语法:

    try:
        ...some functions...
    except Exception, e:
        print(e)

    python3.x捕获异常语法:

    try:
        ...some functions...
    except Exception as e:
        print(e)

    python常见的异常类型:

    1. NameError:尝试访问一个未申明的变量

    >>> v
    NameError: name 'v' is not defined

    2. ZeroDivisionError:除数为0

    >>> v = 1/0
    ZeroDivisionError: int division or modulo by zero

    3. SyntaxError:语法错误

    int int
    SyntaxError: invalid syntax (<pyshell#14>, line 1)

    4. IndexError:索引超出范围

    List = [2]
    >>> List[3]
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        List[3]
    IndexError: list index out of range

    5. KeyError:字典关键字不存在

    Dic = {'1':'yes', '2':'no'}
    >>> Dic['3']
    Traceback (most recent call last):
      File "<pyshell#20>", line 1, in <module>
        Dic['3']
    KeyError: '3'

    6. IOError:输入输出错误

    >>> f = open('abc')
    IOError: [Errno 2] No such file or directory: 'abc'

    7. AttributeError:访问未知对象属性

    >>> class Worker:
     def Work():
      print("I am working")
    
    >>> w = Worker()
    >>> w.a
    Traceback (most recent call last):
      File "<pyshell#51>", line 1, in <module>
        w.a
    AttributeError: 'Worker' object has no attribute 'a'

    8.ValueError:数值错误

    >>> int('d')
    Traceback (most recent call last):
      File "<pyshell#54>", line 1, in <module>
        int('d')
    ValueError: invalid literal for int() with base 10: 'd'

    9. TypeError:类型错误

    >>> iStr = '22'
    >>> iVal = 22
    >>> obj = iStr + iVal;
    Traceback (most recent call last):
      File "<pyshell#68>", line 1, in <module>
        obj = iStr + iVal;
    TypeError: Can't convert 'int' object to str implicitly

    10. AssertionError:断言错误

    >>> assert 1 != 1
    Traceback (most recent call last):
      File "<pyshell#70>", line 1, in <module>
        assert 1 != 1
    AssertionError
    11.MemoryError:内存耗尽异常

    12. NotImplementedError:方法没实现引起的异常

    class Base(object):
        def __init__(self):
            pass
    
        def action(self):
            #抛出异常,说明该接口方法未实现
            raise NotImplementedError

    异常处理:

    1)执行try子句(在关键字try和关键字except之间的语句)
    
    (2)如果没有异常发生,忽略except子句,try子句执行后结束。
    
    (3)如果在执行try子句的过程中发生了异常,那么try子句剩下的部分将被忽略。如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
    (4)如果异常没有与任何except匹配,那么这个异常将会传递给上层的try中。
    
    (5)一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
    (6)一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。
    except (RuntimeError, TypeError, NameError):
            pass

    (7)最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。

    import sys
    
    try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
    except OSError as err:
        print("OS error: {0}".format(err))
    except ValueError:
        print("Could not convert data to an integer.")
    except:
        print("Unexpected error:", sys.exc_info()[0])
        raise

    (8)try except语句还有一个可选的else子句,如果使用这个子句,那么必须放在所有的except子句之后。这个子句将在try子句没有发生任何异常的时候执行。

    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except IOError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()

    (9)异常处理并不仅仅处理那些直接发生在try子句中的异常,而且还能处理子句中调用的函数(甚至间接调用的函数)里抛出的异常。

    >>> def this_fails():
            x = 1/0
       
    >>> try:
            this_fails()
        except ZeroDivisionError as err:
            print('Handling run-time error:', err)
       
    Handling run-time error: int division or modulo by zero

    抛出异常:使用 raise 语句抛出一个指定的异常

    >>> raise NameError('HiThere')
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: HiThere

    raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。

    如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。

    >>> try:
            raise NameError('HiThere')
        except NameError:
            print('An exception flew by!')
            raise
       
    An exception flew by!
    Traceback (most recent call last):
      File "<stdin>", line 2, in ?
    NameError: HiThere

    定义清理行为:

    例1:

    while True:
        try:
            x = int(input('请输入一个数字:'))
            break
        except Exception:  #接收任意错误
            print('您输入的不是一个数字,请重试!')

    输出结果:

    请输入一个数字:e
    您输入的不是一个数字,请重试!
    请输入一个数字:12

    例2:

    def fun(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
        else:
            print("result is", result)
        finally:
            print('---------------')
    
    print(fun(2,1))
    print(fun(2,0))
    print(fun('2','1'))

    输出结果:

    result is 2.0
    ---------------
    None
    division by zero!
    ---------------
    None
    ---------------
    TypeError: unsupported operand type(s) for /: 'str' and 'str'

    以上例子不管try子句里面有没有发生异常,finally子句都会执行。

    注意:如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出。

    预定义的清理行为:

    例:

    for line in open("myfile.txt"):
        print(line, end="")

    以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭。

    关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:

    with open("myfile.txt") as f:
        for line in f:
            print(line, end="")

    以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。

  • 相关阅读:
    HTML中使用Vue+Dhtmlxgantt制作任务进度图
    Vue中使用js-xlsx导出Data数据到Excel
    Vue生命周期
    ajax调用免费的天气API
    maven无法自动下载依赖包settings.xml文件配置
    idea打开项目没有src目录
    java jdk idea maven安装及配置
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/pytorch
    The procedure entry point OPENSSL_sk_new_reserve could not be located in the dynamic link library
    Nuget打包没有注释显示
  • 原文地址:https://www.cnblogs.com/ping-y/p/5849747.html
Copyright © 2011-2022 走看看