2014-01-15 177 views
2

IF語句我有類似下面的方法:最佳實踐與Catch塊

public static addSomething(int id) 
{ 
    string msg = getStringMsg(id); 
    try 
    { 
     //do lots of stuff 
     Console.WriteLine(msg) 
    } 
    catch (Exception e) 
    { 
     if (id == 1) 
      throw new Exception("Exception msg 1: " + msg); 
     else 
      throw new Exception("Exception msg 2: " + msg); 
    } 
} 

是具有令人難以接受的catch塊這樣的條件分支?如果是這樣,我的替代品是什麼?

我想我可以這樣做:

public static addSomething(int id) 
{ 
    string msg = getStringMsg(id); 
    string exceptionMsg; 
    if (id == 1) 
     exceptionMsg = "Exception msg 1: " + msg); 
    else 
     exceptionMsg = "Exception msg 2: " + msg); 
    try 
    { 
     //do lots of stuff 
     Console.WriteLine(msg) 
    } 
    catch (Exception e) 
    { 
     throw new Exception(exceptionMsg); 
    } 
} 

但我真的想保持代碼的try塊外面到最低限度,如果在所有。關於我的第二個問題:是否有一種方法可以在try塊內將getStringMsg(id)分配給msg,但仍然可以在catch塊中訪問它?

+0

對於代碼的可讀性,我會親自去你的第一個例子。我的問題是爲什麼你不會僅僅採用e.Message,msg和id,將其格式化爲您的需要,然後將其泡大。一般來說catch塊是爲了恢復應用程序,而不是用於業務邏輯。 – AWinkle

+0

還有一個問題 - 你是否真的需要將'getStringMsg(id)'返回的'msg'添加到錯誤信息中?你需要什麼東西*部分 - 'msg'或'id',或者他們兩個? –

+0

對第一個問題的回答是肯定的。這是一個非常簡化的版本,可以解決問題的核心問題。是的,我需要在'//很多東西'中使用'msg'和'id'。 – dursk

回答

4

我建議你避免錯誤消息的創建,直到發生錯誤。此外,我建議通過原始異常作爲內部異常給你扔異常(和它的最好創建一些自定義的異常,如果你是plaining把它扔更高水平的應用程序):

public static void addSomething(int id) 
{ 
    string msg = getStringMsg(id); 
    try 
    { 
     //do lots of stuff 
     Console.WriteLine(msg) 
    } 
    catch (Exception e) 
    { 
     string errorMessage = (id == 1) ? 
      "Exception msg 1: " : "Exception msg 2: "; 

     throw new FooException(errorMessage + msg, e); 
    } 
} 
2

我相信你try根據您的參數id,塊也有很多conditional logic。在這種情況下,最好是將實現拆分爲單獨的方法,每個方法都有其自己的try catch塊。

還要考慮重構 - replace conditional with polymorphism

+0

+1 –

0

這很好,但你應該通過拋出異常,因爲你扔什麼的內部異常:

catch (Exception ex) 
{ 
    ... 
     throw new Exception("message", ex); 
    ... 
} 

如果你想重新拋出的處理異常,只需鍵入throw;。不要再扔它。有很多關於差異的文章以及爲什麼單個單詞語句 - throw - 是最好的。