异常处理(exception)

异常 Exception

错误Error

逻辑错误:算法写错了
笔误:例如变量名写错了
函数或类使用错误
总之错误是可以避免的

异常Exception

  这有个前提,没有出现上面所说的错误,也就是说程序写的没有问题,但是在某些情况下,会出现一些意外,导致程序无法正常执行下去。异常不可避免;

  在高级编程语言中,一般都有错误和异常的概念,异常时可以捕获,并处理的,但是错误是不能被捕获的。

产生异常
产生:

raise语句显示的抛出异常
python解释器自己检测到异常并引发它

def foo():
    print('before')

    def bar():
        print(1 / 0)

    bar()

    print('after')


foo()


def _bar():
    print('before')
    raise Exception('my exception')
    print('after')


_bar()

  程序会在异常抛出的地方中断执行,如果不捕获异常,就会提前结束程序(其实是终止当前线程的执行)

raise语句

  raise后什么都没有,表示抛出最近一个被激活的异常,如果没有被激活的异常,则抛类型异常,这种方式很少用,raise后要求应该是BaseException类的子类或实例,如果是类,将被无参实例化。

异常的捕获

try:
  待捕获异常的代码
except[异常类型]:
  异常的处理代码块

try:
    print('begin')
    c = 1 / 0
    print('end')  # 此语句不会执行

except:  # 默认捕获所有类型的异常
    print('catch the exception')
print('outer')

"""
begin
catch the exception
outer
"""
"""异常捕获

"""
import sys


def foo():
    print('before')
    try:  # try会捕获语句块内的异常
        sys.exit(100)
        # raise NotImplementedError()
        # print(1 / 0)  # 待捕获异常的代码块
    except SystemExit:  # 指定捕获异常类型
        print('sys exit')
    print('after')


foo()


class A:
    pass


try:
    # 1 / 0
    # raise A()
    # raise 'abc'  # 注意'abc'不是继承BaseExceptIon类的实例
    raise Exception('错误')  # Exception()是Exception(内建)类的实例

# except ZeroDivisionError as e:
#     print(e)  # division by zero
except Exception as e:
    print('exc ~~~~~~~~~~~~', e)  # exc ~~~~~~~~~~~~ 错误
    print(type(e))  # <class 'Exception'>,e为Exception的实例

还可以捕获指定异常的类型:

try:
    print('begin')
    c = 1 / 0
    print('end')

except ArithmeticError:
    print('catch the exception')
print('outer')

"""
begin
catch the exception
outer
"""

raise真的什么类型都能抛出吗?下面的代码raise全都没有抛出异常

class A:
    pass


try:
    # 1 / 0
    # raise 1
    # raise 'abc'
    raise {}
    # raise A
    # raise A()
except:
    print('catch the exception')

异常类及继承层次

BaseException是所有内建异常类的基类
BaseException
±- SystemExit
±- KeyboardInterrupt
±- GeneratorExit
±- Exception
±- RuntimeError
| ±- RecursionError
±- MemoryError
±- NameError
±- StopIteration
±- StopAsyncIteration
±- ArithmeticError
| ±- FloatingPointError
| ±- OverflowError
| ±- ZeroDivisionError
±- LookupError
| ±- IndexError
| ±- KeyError
±- SyntaxError
±- OSError
| ±- BlockingIOError
| ±- ChildProcessError
| ±- ConnectionError
| | ±- BrokenPipeError
| | ±- ConnectionAbortedError
| | ±- ConnectionRefusedError
| | ±- ConnectionResetError
| ±- FileExistsError
| ±- FileNotFoundError
| ±- InterruptedError
| ±- IsADirectoryError
| ±- NotADirectoryError
| ±- PermissionError
| ±- ProcessLookupError
| ±- TimeoutError

SystemExit

sys.exit()函数引发的异常,异常不捕获处理,就直接交给python解释器,解释器退出。
如果except语句捕获了该异常,则继续向后执行,如果没有捕获住该异常SystemExit,解释器直接退出程序。

except: except后什么都不写,就是捕获所有异常
except 语句可以写多个;
捕获到一个异常就不再往下捕获异常了;

Exception 及子类

Exception是所有内建的、非系统退出的异常的基类,自定义异常应该继承自它。
ArithmeticError所有算术计算引发的异常,其子类有FloatingPointError、OverflowError、ZeroDivisionError。

自定义的异常
# 自定义的异常


class MyException(Exception):
    pass


try:
    raise MyException()  # MyException也是可以的
except MyException:
    print('catch the exception')

异常的捕获

except 可以捕获多个异常
异常捕获规则:捕获从上到下依次比较,如果匹配,则执行匹配的except语句块;
如果一个except语句捕获,其他except语句就不会再次捕获了;
如果没有任何一个except语句捕获这个异常,则该异常向外抛出

class MyException(Exception):
    pass


try:
    a = 1 / 0  # 异常捕获规则:捕获从上到下依次比较,如果匹配,则执行匹配的except语句块
    raise MyException()
    open('a.txt')
except MyException:
    print('catch the MyException')
except ZeroDivisionError:  # 如果一个except语句捕获,其他except语句就不会再次捕获了
    print('1/0')
except Exception:
    print('Exception')  # 如果没有任何一个except语句捕获这个异常,则该异常向外抛出
as子句

被抛出的异常应该是异常的实例,如何捕获这个对象呢?使用as子句

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


try:
    # raise MyException  # raise后跟类名是无参数构造实例,因此需要两个参数
    raise MyException(200, '0k')

except MyException as e:
    print('MyException = {} {}'.format(e.code, e.message))
    # MyException = 200 0k

except Exception as e:
    print('Exception = {}'.format(e))
    # Exception = __init__() missing 2 required positional arguments: 'code' and 'message'
finally字句

最终,即最后一定要执行的,try。。。finally语句中,不管是否发生了异常,都要执行finally的部分

f = None

try:
    f = open('test.txt')  # 相对路径下,没有test.txt文件
except FileNotFoundError as e:
    print('{} {} {}'.format(e.__class__, e.errno, e.strerror))
    # <class 'FileNotFoundError'> 2 No such file or directory
finally:
    print('清理工作')
    # f.close()  # NameError: name 'f' is not defined.解决的办法是在外部定义f
    # # AttributeError: 'NoneType' object has no attribute 'close',因为f根本就不存在,可以做如下修改
    # if f:
    #     f.close()
    # 也可以在finally中再次捕捉异常
    try:
        f.close()
    except AttributeError as e:
        print(e)
        # 'NoneType' object has no attribute 'close'
def foo():
    try:
        return 3
    finally:
        return 5
        print('finally')

    print('==')


print(foo())

进入try,执行return3,虽然函数要返回,但是finally一定还要执行,所以执行return5,函数返回。5被压栈到栈顶,所以返回5.简单说,函数的返回值取决于最后一个return语句,而finally则是try…finally中最后执行的语句块。

异常的传递

def foo1():
    return 1 / 0


def foo2():
    print('foo2 start')
    foo1()
    print('foo2 stop')


foo2()

foo2调用了foo1,foo1产生异常,传递到了foo2中。
异常总是向外抛出,如果外层没有处理这个异常,就会继续向外抛出
如果内层捕获并处理了异常,外部就不能捕获到了
如果到了最外层还是没有被处理,就会中断异常所在的线程的执行。注意整个程序结束的状态返回值


# 线程中测试异常
import threading
import time


def foo1():
    return 1 / 0


def foo2():
    time.sleep(3)
    print('foo2 start')
    foo1()
    print('foo2 stop')


t = threading.Thread(target=foo2)
t.start()
while True:
    time.sleep(1)
    print('Everything OK')
    print(threading.enumerate())  # 打印当前所有线程

线程t直接中断了,只有主线程还在。程序中真正干活的是线程

try:
    try:
        ret = 1 / 0
    except KeyError as e:
        print(e)
    finally:
        print('inner fin')
except ArithmeticError:
    print('outer catch')
finally:
    print('outer fin')

  内部捕获不到异常,会向外部传递异常,但是如果内层有finally且其中有return、break语句,则异常就不会继续向外抛出

def foo():

    try:
        1 / 0
    except KeyError as e:
        print(e)
    finally:
        print('inner fin')
        return  # 异常被压制


try:
    foo()
except ArithmeticError:
    print('outer catch')
finally:
    print('outer fin')

异常的捕获时机

1. 立即捕获

需要立即返回一个明确的结果

def parse_int(s):
    try:
        return int(s)
    except:
        return 0


print(parse_int('s'))
2. 边界捕获

封装产生了边界。
例如:写了有个模块,用户调用这个模块的时候捕获异常,模块内部不需要捕获、处理异常,一旦内部处理了,外部就无法感知了。
例如: 自己写了一个类,使用了open函数,但是出现了异常不知道如何处理,就继续向外层抛出,一般来说最外层也是边界,必须处理这个异常了,否则线程退出。

else子句

try:
    ret = 1 * 0
except ArithmeticError as e:
    print(e)
else:
    print('OK')
finally:
    print('fine')

else子句:没有任何异常发生,则执行。

总结

异常总结

try工作原理

  1. 如果try中语句执行时发生异常,搜索except子句,并执行第一个匹配该异常的except子句
    2.如果try中语句执行时发生异常,却没有匹配的except子句,异常将被递交到外层的try,如果外层不处理这个异常,异常将继续向外层传递。如果都不处理该异常,则会传递到最外层,如果还没有处理,就终止异常所在的线程==
  2. 如果在try执行时没有发生异常,如有else子句,可执行else子句中的语句
  3. 无论try中是否发生异常,finally子句最终都会执行。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值