Python 异常处理 详解

1、错误和异常

1.1 错误 Error

  • 逻辑错误:算法写错了,例如加法写成了减法
  • 笔误:例如变量名写错了,语法错误
  • 函数或类使用错误:其实这也属于逻辑错误
  • 总之,错误是可以避免的

1.2 异常 Exception

  • 异常就是意外情况
  • 在没有出现上述错误的前提下,也就是说程序写的没有问题,但是在某些情况下,会出现一些意外,导致程序无法正常执行下去
  • 例如,访问一个网络文件,突然断网了,这就是个异常,是个意外的情况
  • 总之,异常是不可能避免的

1.3 总结

  • 错误和异常:在高级编程语言中,一般都有错误和异常的概念,异常是可以捕获的,并被处理的,但是错误是不能被捕获的
  • 一个健壮的程序,尽可能的避免错误,尽可能的捕获、处理各种异常

2、产生异常

  • 1 raise 语句显式的抛出异常

  • 2 Python 解释器自己检测到异常并引发它

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

    def foo():
        print('before')
        print(1/0)  # 捕获异常 
        print('after')
    
    foo()
    # ZeroDivisionError: division by zero
    
    def foo():
        print('before')
        raise Exception('My Exception')  # raise 主动抛出异常 
        print('after')
    
    foo()
    # Exception: My Exception
    

3、捕获异常

3.1 语法

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

3.2 示例 1

  • 此例执行到c = 1/0时产生异常并抛出,由于使用了try...except语句块则捕捉到了这个异常

  • 异常生成位置之后语句块将不再执行,转而执行对应的except部分的语句

  • 最后执行try...except语句块之外的语句

    def foo():
        try:
            print('before')
            c = 1/0
            print('after')
        except:
            print('error')
            
        print('catch the exception')
    
    foo()
    print('====== end ======')
    
    before
    error
    catch the exception
    ====== end ======
    

3.3 示例 2

def foo():
    try:
        print('before')
        print(1/0)
        print('after')
    except ArithmeticError:  # 指定捕获的类型
        print('error')

    print('catch the exception')

foo()
print('====== end ======')
before
error
catch the exception
====== end ======

4、 异常类

4.1 Exception hierarchy

The class hierarchy for built-in exceptions is:
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值