logo
Loading...

Day 5-2: 如何自訂例外處理(not enough values to unpack、catching classes that do not inherit from BaseException is not allowed) - Cupoy

我正在嘗試自訂例外處理,如下所示,eb 繼承 ea,ea1、eb1、eb2 提供例外發生時的相關訊息...

try-except

Day 5-2: 如何自訂例外處理(not enough values to unpack、catching classes that do not inherit from BaseException is not allowed)

2020/08/16 下午 03:59
機器學習共學討論版
hungkai
觀看數:53
回答數:1
收藏數:0
try-except

我正在嘗試自訂例外處理,如下所示,eb 繼承 ea,ea1、eb1、eb2 提供例外發生時的相關訊息。但無法順利回傳訊息。

當我進行測試時,我期望將 ea1 的值改為 'not default',利用 `print(ex.args)` 輸出,但出現了錯誤訊息: catching classes that do not inherit from BaseException is not allowed。我嘗試去理解[這個問題](https://stackoverflow.com/questions/53148112/python-3-handling-error-typeerror-catching-classes-that-do-not-inherit-from-bas),但我目前還是無法處理它。

另外,若我不去改變 ea1 的值,在 ea 例外中 `ex.args` 的輸出並不同於類別的預設值而僅為 '( )'。由 eb 的錯誤訊息(not enough values to unpack),我發現它們都沒有回傳值。

我希望能得到"類似於"以下在[Python docs](https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions)範例中的效果,即在發生例外 `Exception` 時,能回傳相對應的訊息 `.args`。"類似於"是因為我所自訂的例外處理有包含繼承關係,與以下情況可能不太相同。

非常感謝!

回答列表

  • 2020/08/16 下午 04:15
    張維元 (WeiYuan)
    贊同數:0
    不贊同數:0
    留言數:3

    嗨,你的問題有點多,我不太知道要從何回答起,第一個要自定義的 Excepetion 應該是這樣寫:


    ```

    for cls in [ea, eb]:

       try:

           raise cls('not default')

       except cls as ex: 

           print("error name: ea")

           print('ex.args =', ex.args)

    ```


    後面衍伸的問題你再看一下,改成這樣寫還有沒有。


    如果這個回答對你有幫助請主動點選「有幫助」或「最佳解答」的按鈕,也可以追蹤我的GITHUB 帳號。若還有問題的話,也歡迎再開一個新的問題繼續發問,或者把你理解的部分整理上來,我都會提供你 Review 和 Feedback 😃😃😃另外我目前有舉辦一個社群活動:學員限定!CUPOY 馬拉松線上小聚 👨🏻‍💻👨🏻‍💻,歡迎一起來玩玩!