日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

作者:youhebuke225 ? 更新時間: 2022-10-11 編程語言

引言

眾所周知,在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,除非要對每一特殊異常進行特殊處理。

總結

原文鏈接:https://blog.csdn.net/youhebuke225/article/details/124365365

欄目分類
最近更新