我正在製作一個小型Python模塊。我希望這個模塊返回錯誤,如果有的話。什麼是在Python中創建錯誤對象的正確或標準方法?如何製作正確的錯誤對象?
編輯:我真的不知道如何創建我自己的錯誤,當然,因爲我不知道錯誤是如何工作的(我只知道如何在try: ... except: ...
中捕獲它們)。 所以,現在我製作了草稿錯誤消息,錯誤是字符串。當出現意想不到的情況時,我會打印和return None
。我想這是不正確的方法:)
例子:
...
self.IsNotStringError = "Args was not a string."
...
def myMethod(self, args)
""" Args must be a string. """
if not isinstance(args, str):
print IsNotStringError
return None
else:
do things...
編輯(之二):在閱讀下面的答案,我已進一步看着Python文檔。有a tutorial on how to make user-defined exceptions。從文檔
例子:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
謝謝。我不明白你爲什麼在你的異常之後「傳遞」,也不知道錯誤消息爲什麼沒有在YourError類中定義。你能解釋一下嗎? – Benjamin 2011-05-15 08:31:07
沒關係,我找到[documentation](http://docs.python.org/tutorial/errors.html#tut-userexceptions) – Benjamin 2011-05-15 08:43:19