亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

處理捕獲的異常并在 try 塊之外引發異常的正確方法是什么

處理捕獲的異常并在 try 塊之外引發異常的正確方法是什么

喵喵時光機 2022-12-27 14:46:12
我剛剛開始我的 python 學習之旅,需要一些幫助以正確的方式引發異常??紤]一個循環遍歷列表并執行任務的代碼塊。如果發生異常,則繼續執行程序。并執行其余代碼。在程序結束時引發異常并使用非零代碼系統化應用程序。這個想法是程序應該繼續執行所有任務,但退出時使用非 0 代碼供外部應用程序跟蹤和報告。save_exc_info = Nonedef numMatcher(numbers):    try:        if numbers != 2:            print('number match ' + str(numbers))        else:            raise ValueError('Number not in list. Will be logged for troubleshooting')  # raise exception and log it    except ValueError as veer:  # exception 1 caught and saved        save_exc_info = sys.exc_info()    except (IOError, OSError) as ioerr:  # exception 2 caught and saved        save_exc_info = sys.exc_info()try:    print('Next step')  # Perform rest of the tasks in the codeexcept Exception as excp:  # exception 3 caught and saved    save_exc_info = sys.exc_info()print('final step')numlist = [1, 2, 3]for numbers in numlist:    numMatcher(numbers)if save_exc_info is not None:    traceback.print_exception(*save_exc_info)  # how to return the right exception and print?    sys.exit(1)  # At the end of the program, exit with non zero code as there was an exception in the program.
查看完整描述

1 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

在處理異常時,可以將其賦值給一個變量,例如:


    except AssertionError as aerr:

        saved_exception = aerr

您以后可以訪問它,例如:


print(saved_exception)

對于您的代碼,這為您提供了沒有兩個變量的選項,而isError不僅僅是使用saved_exception = None和稍后測試if saved_exception is not None: ...


不確定為以后保存異常(將其用作傳遞信息的通用接口)有多大用處。也許值得重新考慮一下。


N Chauhan在評論中也提出了一個很好的觀點,即AssertionError不是非常適合用來傳達此類信息的異常。


對于您更新的問題。如果你想打印回溯是你會在引發異常時看到它,最直接的可能是保存異常信息并使用print_exception()(或它的format_exception朋友):


except ValueError:

    save_exc_info = sys.exc_info()            

...

traceback.print_exception(*save_exc_info) 

您也可以從/使用保存的異常中提取相同的信息,*save_exc_info也可以是:(type(saved_exception), saved_exception, saved_exception.__traceback__對于第一個示例中的保存異常)。


查看完整回答
反對 回復 2022-12-27
  • 1 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號