2017-02-22 71 views
0

我想寫一個類,它可以處理在我的應用程序中引發的錯誤。這樣我就可以在一個類中更改錯誤消息的格式。Python自定義錯誤類來處理異常

class ErrorMessage(Exception): 
    def __init__(self, error, classname): 
     self.error = error 
     self.classname = classname 
     self.errormsg = "scriptname.py, {0}, error={1}".format(self.classname, self.error) 
     print self.errormsg 

class LoadFiles(): 
    try: 
     something-bad-causes-error 
    except Exception,e: 
     raise ErrorMessage(e, "LoadFiles") 

此刻我的腳本打印機自定義錯誤,但它繼續退出這一行之前打印的完整回溯「提高的ErrorMessage(即‘LoadFiles’)」

scriptname.py, LoadFiles, error= LoadFiles instance has no attribute 'config' 
Traceback (most recent call last): 
File "run.py", line 95, in <module> 
    scriptname().main() 
File "run.py", line 54, in main 
    self.loadfiles() 
File "run.py", line 45, in loadfiles 
    "removed" = LoadFiles(self.commands).load_files() 
File "dir/core/loadfiles.py", line 55, in load_files 
    raise ErrorMessage(e, "LoadFiles") 
scriptname.core.errormessage.ErrorMessage 

任何想法如何解決這個問題?

感謝

+0

爲什麼你還在使用'except Exception,e:'語法?新的語法支持[從2.6](https://docs.python.org/2/whatsnew/2.6.html#pep-3110-exception-handling-changes),現在已經超過8年了。 – jonrsharpe

+1

爲什麼LoadFiles是一個類?它對我來說看起來像一個功能。 – tyteen4a03

+0

我知道這是一個旁白,但如果你還沒有,看一看標準的例外和警告套件。可能有一個適合你的用例。 – rshield

回答

0

如果你只需要在這個錯誤退出腳本,不引發異常,只是打印錯誤並退出。而且它的,即使你不需要你的例外是可重複使用的簡單:

try: 
    something-bad-causes-error 
except Exception as e: 
    print("scriptname.py, LoadFiles, error={0}".format(e)) 
    sys.exit(1) 

而且這將是更好地使用logging模塊打印錯誤。

0

我認爲你錯過了自定義異常的意義,創建一個異常類意味着你的程序的某些函數或邏輯會拋出這個自定義異常,你將能夠捕獲並處理它。如果你正在尋找只是解析輸出,沒有必要創建一個自定義類:

try: 
    something_bad # will raise maybe IndexError or something 
except Exception as e: 
    print e.message 

雖然使用自定義類:

class DidNotHappen(Exception): 
    def __init__(*args, **kwargs): 
    # do something here 

def my_function(something_happens): 
    if somehting_happens: 
    cool 
    else: 
    raise DidNotHappen 

my_function(True) # cool 
my_function(False) # Raises DidNotHappen exception 

的關鍵是要提高

什麼異常

祝你好運!