Python中的异常处理

来源:互联网 发布:sql删除视图数据 编辑:程序博客网 时间:2024/06/07 02:38

注意:本篇博客适用于Python3

一、try…except

有时候我们写程序的时候,会出现一些错误或异常,导致程序终止。例如,做除法时,除数为0,会引起一个ZeroDivisionError

例子:

程序代码:a=10b=0c=a/bprint("done")运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pyTraceback (most recent call last):  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 66, in <module>    c=a/bZeroDivisionError: division by zeroProcess finished with exit code 1

我们发现程序因为ZeroDivisionError而中断了,语句print “done” 没有运行。为了处理异常,我们使用try…except,更改代码:

程序代码:a=10b=0try:    c=a/b    print(c)except ZeroDivisionError as e:    print(e)print ("done")运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pydivision by zerodoneProcess finished with exit code 0

这样程序就不会因为异常而中断,从而print (”done“)语句正常执行。

注意:
我们把可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,也可以处理一组圆括号中的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except

处理一组异常可以这样写(其中e代表异常的实例):

程序代码:a=10b=0try:    c=a/b    print(c)except ZeroDivisionError as e:    print(e)except IOError as e:                 ##依次罗列即可    print(e)print ("done")

try ….except…else 语句,当没有异常发生时,else中的语句将会被执行。

例子:

程序代码:a=10b=10try:    c=a/b    print(c)except ZeroDivisionError as e:    print(e)except IOError as e:    print(e)else:    print ("done")运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py1.0doneProcess finished with exit code 0
程序代码:a=10b=0try:    c=a/b    print(c)except ZeroDivisionError as e:    print(e)except IOError as e:    print(e)else:    print ("done")运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pydivision by zeroProcess finished with exit code 0

二、raise 引发一个异常

# 自定义绝对值函数def my_abs(x):    if not isinstance(x,(int,float)):        raise TypeError('bad operand type')   ##输入的必须是整数或者浮点数,否则,抛出异常    if x >= 0:        return x    else:        return -xprint(my_abs('A'))运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pyTraceback (most recent call last):  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 9, in <module>    print(my_abs('A'))  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 4, in my_abs    raise TypeError('bad operand type')TypeError: bad operand typeProcess finished with exit code 1

三、try …finally

无论异常是否发生,在程序结束前,finally中的语句都会被执行。

程序代码:a=10b=0try:    print(a/b)finally:    print("always excute")运行结果:"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pyalways excuteTraceback (most recent call last):  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 79, in <module>    print(a/b)ZeroDivisionError: division by zeroProcess finished with exit code 1

四、自定义一个异常类

自定义一个MyException类,继承Exception。

class MyException(Exception):    def __init__(self,message):        Exception.__init__(self)        self.message=message

如果输入的数字小于10,就引发一个MyException异常:

import MyExceptiona=input("please input a num:")if int(a)<10:    try:        raise MyException("my excepition is raised ")    except MyException as e:        print(e)
运行结果1(正常):"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pyplease input a num:56Process finished with exit code 0运行结果2(异常):"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.pyplease input a num:5Traceback (most recent call last):  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 88, in <module>    raise MyException("my excepition is raised ")TypeError: 'module' object is not callableDuring handling of the above exception, another exception occurred:Traceback (most recent call last):  File "C:/Users/Administrator/PycharmProjects/Test/MyDefineFun.py", line 89, in <module>    except MyException as e:TypeError: catching classes that do not inherit from BaseException is not allowedProcess finished with exit code 1

五、python所有的标准异常类:

     异常名称                                描述BaseException                      所有异常的基类 SystemExit                         解释器请求退出 KeyboardInterrupt                  用户中断执行(通常是输入^C) Exception                          常规错误的基类 StopIteration                      迭代器没有更多的值 GeneratorExit                      生成器(generator)发生异常来通知退出 SystemExit Python                  解释器请求退出 StandardError                      所有的内建标准异常的基类 ArithmeticError                    所有数值计算错误的基类 FloatingPointError                 浮点计算错误 OverflowError                      数值运算超出最大限制 ZeroDivisionError                  除(或取模)零 (所有数据类型) AssertionError                     断言语句失败 AttributeError                     对象没有这个属性 EOFError                           没有内建输入,到达EOF 标记 EnvironmentError                   操作系统错误的基类 IOError                            输入/输出操作失败 OSError                            操作系统错误 WindowsError                       系统调用失败 ImportError                        导入模块/对象失败 KeyboardInterrupt                  用户中断执行(通常是输入^C) LookupError                        无效数据查询的基类 IndexError                         序列中没有没有此索引(index) KeyError                           映射中没有这个键 MemoryError                        内存溢出错误(对于Python 解释器不是致命的) NameError                          未声明/初始化对象 (没有属性) UnboundLocalError                  访问未初始化的本地变量 ReferenceError                     弱引用(Weak reference)试图访问已经垃圾回收了的对象 RuntimeError                       一般的运行时错误 NotImplementedError                尚未实现的方法 SyntaxError Python                 语法错误 IndentationError                   缩进错误 TabError Tab                       和空格混用 SystemError                        一般的解释器系统错误 TypeError                          对类型无效的操作 ValueError                         传入无效的参数 UnicodeError Unicode               相关的错误 UnicodeDecodeError Unicode         解码时的错误 UnicodeEncodeError Unicode         编码时错误 UnicodeTranslateError Unicode      转换时错误 Warning                            警告的基类 DeprecationWarning                 关于被弃用的特征的警告 FutureWarning                      关于构造将来语义会有改变的警告 OverflowWarning                    旧的关于自动提升为长整型(long)的警告 PendingDeprecationWarning          关于特性将会被废弃的警告 RuntimeWarning                     可疑的运行时行为(runtime behavior)的警告 SyntaxWarning                      可疑的语法的警告 UserWarning                        用户代码生成的警告