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

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

處理類內的錯誤,但在其他腳本中引發錯誤?

處理類內的錯誤,但在其他腳本中引發錯誤?

喵喔喔 2023-04-18 15:07:42
我正在尋找一種可靠且實用的方法來在類實例中存儲不同的錯誤和/或異常(即IOError、ValueError、等),但避免立即對它們進行 -ing 處理。相反,我想以某種方式將它們傳達給首先編輯和創建類實例的腳本,以及那里的錯誤和異常。<CustomError>raiseimportraise我不是在尋找有關如何捕獲異常的策略。對于我的自定義異常,我使用類!有沒有通用的方法?
查看完整描述

1 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

您可以定義一個“容器/收集器”類,其中包含您的自定義異常(當然,不引發)。在我的示例中,這個收集器調用就是MyExceptions類。

您可以將唯一異常定義為從相關內置異常繼承的類。

唯一異常的基本語法:

class MyException1(BaseException):

? ? """

? ? Exception is inherited from 'BaseException'.

? ? """

? ? def __str__(self):

? ? ? ? return "This is my Exception1. Inherited from 'BaseException'"

__str__您可以使用或魔術方法設置異常消息(我在示例中__repr__使用了)。__str__這意味著,在上面的示例中,如果您引發MyException1異常,那么回溯中的消息將為This is my Exception1. Inherited from 'BaseException'.?

my_exceptions.py:

class MyExceptions(object):

? ? """

? ? Collector class of Unique Exceptions

? ? """


? ? class MyException1(BaseException):

? ? ? ? """

? ? ? ? Exception is inherited from 'BaseException'.

? ? ? ? """

? ? ? ? def __str__(self):

? ? ? ? ? ? return "This is my Exception1. Inherited from 'BaseException'"


? ? class MyException2(Exception):

? ? ? ? """

? ? ? ? Exception is inherited from 'Exception'.

? ? ? ? """

? ? ? ? def __str__(self):

? ? ? ? ? ? return "This is my Exception2. Inherited from 'Exception'"


? ? class MyValueError(ValueError):

? ? ? ? """

? ? ? ? Exception is inherited from 'ValueError'.

? ? ? ? """

? ? ? ? def __str__(self):

? ? ? ? ? ? return "This is my MyValueError. Inherited from 'ValueError'"


? ? class AttributeError(BaseException):

? ? ? ? """

? ? ? ? Redefined 'AttributeError'. Inherited from 'ValueError'

? ? ? ? """

? ? ? ? def __str__(self):

? ? ? ? ? ? return "Redefined 'AttributeError'. Inherited from 'ValueError'"

正如您在上面看到的,我的異常收集器類是MyExceptions. 這個類包含其他類,實際上這些是唯一的例外。我寫了更多類型的異常。獨特的異常繼承自不同的內置異常,最后一個異常顯示了如何重新定義內置異常(或多或少)。


這些異常的使用(test.py):


import my_exceptions



def raise_my_exception1():

? ? raise my_exceptions.MyExceptions.MyException1



def raise_my_exception2():

? ? raise my_exceptions.MyExceptions.MyException2



def raise_my_value_error():

? ? raise my_exceptions.MyExceptions.MyValueError



def raise_my_attribute_error():

? ? raise my_exceptions.MyExceptions.AttributeError



def raise_original_attribute_error():

? ? raise AttributeError("This is the original (built-in) AttributeError exception")



function_list = [

? ? raise_my_exception1,

? ? raise_my_exception2,

? ? raise_my_value_error,

? ? raise_my_attribute_error,

? ? raise_original_attribute_error,

]


for func in function_list:

? ? try:

? ? ? ? func()

? ? except BaseException as e:

? ? ? ? print(e)

test.py正如您在我上面的文件中看到的,我已將該my_exceptions.py文件導入為 Python 模塊(導入 my_exceptions)。函數中會引發獨特的異常。您可以訪問例外情況:<Module.CollectorClass.Exception>。最后一個raise_original_attribute_error函數使用自定義消息引發內置AttributeError(它顯示了如何將自己的AttributeError異常與內置異常分開AttributeError)。該function_list列表包含函數的引用(使用此解決方案,我可以在 for 循環中調用函數,而無需逐個調用它們)。在 for 循環中,我定義了一個try/except結構并調用了函數。我使用了BaseException內置異常,因為它是 Python 中范圍更廣的異常。


腳本輸出:


>>> python2 test.py?

This is my Exception1. Inherited from 'BaseException'

This is my Exception2. Inherited from 'Exception'

This is my MyValueError. Inherited from 'ValueError'

Redefined 'AttributeError'. Inherited from 'ValueError'

This is the original (built-in) AttributeError exception

你可以在 try/except 中捕獲你自己的異常(與其他的分開):


import my_exceptions



def raise_my_exception1():

? ? raise my_exceptions.MyExceptions.MyValueError



def raise_other_exception():

? ? raise Exception("Unexpected exception")


for func in [raise_my_exception1, raise_other_exception]:

? ? try:

? ? ? ? func()

? ? except my_exceptions.MyExceptions.MyValueError as e:

? ? ? ? print(e)

? ? ? ? print("Handled exception. Do nothing!")

? ? except Exception as e:

? ? ? ? print(e)

? ? ? ? print("Not handled exception. Raise it!")

? ? ? ? raise e

輸出:


>>> python2 test.py?

This is my MyValueError. Inherited from 'ValueError'

Handled exception. Do nothing!

Unexpected exception

Not handled exception. Raise it!

Traceback (most recent call last):

? File "test.py", line 20, in <module>

? ? raise e

Exception: Unexpected exception

當然,您有很多選擇來使用這個自己的異常收集器。


您可以從異常收集器類創建一個實例:


import my_exceptions


exception_collector = my_exceptions.MyExceptions()



def raise_my_exception1():

? ? raise exception_collector.MyValueError

如果您是一個嚴格的OOP開發人員,您可以從您的異常類繼承您的“功能”類。在這種情況下,您可以將異常用作“實例異?!保◣в衧elf)??赡苓@就是您要找的東西!


例子:


import my_exceptions



class FunctionalClass(my_exceptions.MyExceptions):

? ? def raise_my_exception1(self):

? ? ? ? raise self.MyValueError


? ? def raise_other_exception(self):

? ? ? ? raise Exception("Unexpected exception")



functional_instance = FunctionalClass()


for func in [functional_instance.raise_my_exception1, functional_instance.raise_other_exception]:

? ? try:

? ? ? ? func()

? ? except my_exceptions.MyExceptions.MyValueError as e:

? ? ? ? print(e)

? ? ? ? print("Handled exception. Do nothing!")

? ? except Exception as e:

? ? ? ? print(e)

? ? ? ? print("Not handled exception. Raise it!")

? ? ? ? raise e

輸出:


>>> python2 test.py?

This is my MyValueError. Inherited from 'ValueError'

Handled exception. Do nothing!

Unexpected exception

Not handled exception. Raise it!

Traceback (most recent call last):

? File "test.py", line 23, in <module>

? ? raise e

Exception: Unexpected exception


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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