在現代Python中聲明自定義異常的正確方法? - Proper way to declare custom exceptions in modern Python?

問題:

What's the proper way to declare custom exception classes in modern Python? 在現代Python中聲明自定義異常類的正確方法是什麼? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception. 個人主要目標是遵循其餘異常類具備的任何標準,以便(例如)我捕獲到異常中的任何工具都會打印出我包含在異常中的任何多餘字符串。 python

By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. 「現代Python」是指能夠在Python 2.5中運行但對於Python 2.6和Python 3. *是「正確」的方式。 And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception. 所謂「自定義」,是指一個Exception對象,該對象能夠包含有關錯誤緣由的其餘數據:字符串,也許還包括與該異常相關的其餘任意對象。 工具

I was tripped up by the following deprecation warning in Python 2.6.2: 我在Python 2.6.2中被如下棄用警告絆倒了: spa

>>> class MyError(Exception):
...     def __init__(self, message):
...         self.message = message
... 
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

It seems crazy that BaseException has a special meaning for attributes named message . BaseException對於名爲message屬性有特殊含義彷佛很瘋狂。 I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? 我從PEP-352收集到,該屬性確實在2.5中有特殊含義,所以他們想棄用該屬性,因此我猜測如今禁止使用該名稱(以及一我的)。 Ugh. 啊。 .net

I'm also fuzzily aware that Exception has some magic parameter args , but I've never known how to use it. 我也模糊地知道Exception有一些魔術參數args ,可是我歷來不知道如何使用它。 Nor am I sure it's the right way to do things going forward; 我也不肯定這是前進的正確方法。 a lot of the discussion I found online suggested they were trying to do away with args in Python 3. 我在網上發現的不少討論都代表他們正在嘗試消除Python 3中的args。 code

Update: two answers have suggested overriding __init__ , and __str__ / __unicode__ / __repr__ . 更新:有兩個答案建議覆蓋__init____str__ / __unicode__ / __repr__ That seems like a lot of typing, is it necessary? 好像要打不少筆,有必要嗎? 對象


解決方案:

參考一: https://stackoom.com/question/5XI7/在現代Python中聲明自定義異常的正確方法
參考二: https://oldbug.net/q/5XI7/Proper-way-to-declare-custom-exceptions-in-modern-Python
相關文章
相關標籤/搜索