欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年08月16日 09:35:31   作者:youhebuke225  
有時(shí)候我們寫程序的時(shí)候,會出現(xiàn)一些錯誤或異常,導(dǎo)致程序終止,使用try…except,這樣程序就不會因?yàn)楫惓6袛?下面這篇文章主要給大家介紹了關(guān)于python嵌套try...except如何使用的相關(guān)資料,需要的朋友可以參考下

引言

眾所周知,在python中我們用try…except…來捕獲異常,使用raise來拋出異常,但是多重的try…except…是如何使用的呢

前提

拋出異常

當(dāng)調(diào)用raise進(jìn)行拋出錯誤的時(shí)候,拋出錯誤的后面的代碼不執(zhí)行

def func():
    print("hello")
    raise Exception("出現(xiàn)了錯誤")
    print("world")

func()

打印的錯誤堆棧

如果抓取錯誤,就相當(dāng)于if...else,并不會打斷代碼的執(zhí)行

def func():
    try:
        print("hello")
        raise Exception("出現(xiàn)了錯誤")
    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 是多有異常的父類,他會捕獲所有的異常
  • 其后面會跟一個(gè)as as后面的變量就是異常對象,異常對象是異常類實(shí)例化后得到的

多重try

如果是嵌套的try...except...的話,這一層raise的錯誤,會被上一層的try...except...進(jìn)行捕獲

補(bǔ)充:捕獲異常的小方法

方法一:捕獲所有異常

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

運(yùn)行:

<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()

運(yùn)行:

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])

運(yùn)行:

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

注意:萬能異常Exception

被檢測的代碼塊拋出的異常有多種可能性,并且我們針對所有的異常類型都只用一種處理邏輯就可以了,那就使用Exception,除非要對每一特殊異常進(jìn)行特殊處理。

總結(jié)

到此這篇關(guān)于python嵌套try...except如何使用的文章就介紹到這了,更多相關(guān)python嵌套try...except使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論