python嵌套try...except如何使用详解

2022-08-16 14:06:58
目录
引言前提抛出异常自定义异常异常对象多重try补充:捕获异常的小方法方法一:捕获所有异常方法二:采用traceback模块查看异常方法三:采用sys模块回溯最后的异常总结

引言

众所周知,在python中我们用try…except…来捕获异常,使用raise来抛出异常,但是多重的try…except…是如何使用的呢

前提

抛出异常

当调用raise进行抛出错误的时候,抛出错误的后面的代码不执行

def func():
    print("hello")
    raise Exception("出现了错误")
    print("world")

func()

打印的错误堆栈

如果抓取错误,就相当于if...else,并不会打断代码的执行

def func():
    try:
        print("hello")
        raise Exception("出现了错误")
    except Exception as why:
        print(why)
        print("world")

func()

自定义异常

自定义异常需要我们继承异常的类,包括一些框架中的异常的类,我们自定义异常的话都需要继承他们

class MyError(Exception):
    pass

def say_hello(str):
    if str != "hello":
        raise MyError("传入的字符串不是hello")
    print("hello")

say_hello("world")

异常对象

    Exception>其后面会跟一个as as后面的变量就是异常对象,异常对象是异常类实例化后得到的

    多重try

    如果是嵌套的try...except...的话,这一层raise的错误,会被上一层的try...except...进行捕获

    补充:捕获异常的小方法

    方法一:捕获所有异常

    a=10
    b=0
    try:
        print (a/b)
    except Exception as e:
        print(Exception,":",e)
    finally:
        print ("always excute")
    

    运行:

    <class 'Exception'> : division by zero
    always excute

    方法二:采用traceback模块查看异常

    import traceback   
    try:
        print ('here1:',5/2)
        print ('here2:',10/5)
        print ('here3:',10/0)
        
    except Exception as e:
        traceback.print_exc()
    

    运行:

    here1: 2.5
    here2: 2.0
    Traceback (most recent call last):
      File "/Users/lilong/Desktop/online_release/try_except_use.py", line 59, in <module>
        print ('here3:',10/0)
    ZeroDivisionError: division by zero

    方法三:采用sys模块回溯最后的异常

    import sys   
    try:
        print ('here1:',5/2)
        print ('here2:',10/5)
        print ('here3:',10/0)
        
    except Exception as e:
        info=sys.exc_info()  
        print (info[0],":",info[1])
    

    运行:

    here1: 2.5
    here2: 2.0
    <class 'ZeroDivisionError'> : division by zero

    注意:万能异常Exception

    被检测的代码块抛出的异常有多种可能性,并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception,除非要对每一特殊异常进行特殊处理。

    总结

    到此这篇关于python嵌套try...except如何使用的文章就介绍到这了,更多相关python嵌套try...except使用内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!