异常处理

当程序出现错误的时候,进行捕捉,然后根据捕捉到的错误信息进行对应的处理

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs.

try:
    code
except (Error1,Error2) as e: # 多种错误统一处理
    print(e)

# except Exception: # 捕获所有错误,不建议使用,不知道具体什么错误
#     print("未知错误")

else:
    print("一切正常" ) # 没有任何错误,执行else
finally:
    print("不管有没有错,都执行")

初识异常处理

如: 让用户进行输入,提示用户输入一个数字,如果输入的是一个数字,那么就把输入的数字转换为int类型,然后输出用户输入的数字,如果用户输入的不是一个数字,那么类型转换就会出错,如果出错,就提示用户“输入类型错误,你应该输入一个数字”

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

try:
    n = int(input("请输入一个数字>>> "))
    print("你输入的数字是: ",n)
except Exception as e:
    print("输入类型错误,你应该输入一个数字.")

输出

➜  python_test python3 020-exercise-1.py
请输入一个数字>>> 3
你输入的数字是:  3
➜  python_test python3 020-exercise-1.py
请输入一个数字>>> fad
输入类型错误,你应该输入一个数字.

异常分类

常用异常

对不同的异常进行不同的处理

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

try:
    n = int(input("请输入一个数字>>> "))
except ValueError as e:
    print("ValueError")
except Exception as e:
    print("出现异常")

输出

➜  python_test python3 020-exercise-2.py
请输入一个数字>>> 1231
➜  python_test python3 020-exercise-2.py
请输入一个数字>>> dfa
ValueError

在处理异常时,如果出现错误,那么会首先匹配ValueError,然后再匹配Exception

捕获多个错误

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

try:
    raise IndexError("出错了")
except (IndexError,NameError) as e:  # 捕获括号内的错误,并把错误信息赋值给e
    print(e)

错误异常的基本结构

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

执行流程

  1. 如果出现错误,那么就执行except代码块,然后再执行finally
  2. 如果没有出现错误,那么就执行else代码块,然后再执行finally
  3. 不管有没有出现异常都会执行finally

主动触发异常

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

try:
    # raise表示主动触发异常,然后创建一个Exception对象,Exception括号内的值就是Exception对象的值
    raise Exception("主动触发异常")
except Exception as e:
    # 输出Exception对象的值
    print(e)
➜  python_test python3 020-exercise-4.py
主动触发异常

如果需要捕获和处理一个异常,又不希望异常在程序中死掉,一般都会利用raise传递异常

>>> try:
...   raise IndexError('Index')
... except IndexError:
...   print('error')
...   raise
...
error
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: Index

断言

如果条件成立则成立,如果条件不成立则报错

>>> assert 1 == 1
>>> assert 1 == 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

自定义异常

用户自定义的异常通过类编写,且通常需要继承Exception内置的异常类,基于类的异常允许脚本建立异常类型,继承行为以及附加状态信息.

>>> class Bar(Exception):
...   pass
...
>>> def doomed():
...   raise Bar()
...
>>> try:
...   doomed()
... except Bar as e:
...   print("error")
...
error

如果要自定义错误显示信息,我们只需要在类中定义字符串重载(__str__,__repr__)方法中的其中一个即可:

>>> class MyError(Exception):
...   def __str__(self):
...     return "出错了."
...
>>> try:
...   raise MyError()
... except MyError as e:
...   print(e)
...
出错了.
class XxxException(Exception):

    def __init__(self,msg):
        self.message = msg

    # 下面可以不写__str__  Exception里面已经定义了,默认是msg
    def __str__(self):
        return self.message

try:
    raise XxxException('xxx')
except XxxException as e:
    print(e)