2016-02-12 96 views
1

我在userinfo表中有一些用戶信息,如果代碼執行失敗意味着控制將會捕獲塊,我可以在catchy塊中返回什麼。在catch塊中返回什麼

public static UsersInfo GetById(int Userid) 
    { 
     if (Userid <= null) 
     { 
      throw new ArgumentNullException(); 
     } 
     try 
     { 
      UnitOfWork unitofwork = new UnitOfWork(); 
      var user = unitofwork.UserInfoRepository.GetByID(Userid); 
      return user; 
     } 
     catch(Exception ex) 
     { 
     // What to return in catch block ? 

     } 

    } 
+0

那麼,在這種情況下,它已經到了要返回的東西了。您可以根據您的需要返回'null'或者'UsersInfo'的某種填充實例作爲「默認」值。 –

+0

你想從'catch'返回什麼? – Dennis

+0

這取決於你想要的。您可以向呼叫者拋出異常,以便呼叫者知道呼叫有什麼問題。在投擲之前,您可能需要記錄異常以便以後進行故障排除和分析。如果調用者不需要知道錯誤,那麼你可以返回null。 – Adil

回答

0

你必須可以實現什麼不同的選項(所以它的你來決定

選項1:當你的代碼進入catch塊像

可以拋出一個異常
catch (Exception ex) 
{ 
    throw new SomeException(ex); 
} 

選項2:您可以爲您的用戶恢復默認值像

catch(Exception ex) 
{ 
    return "some value"; 
} 

方案3:您可以顯示顯示異常的消息像

catch(Exception ex) 
{ 
    MessageBox.Show(ex.message); 
    return "some value or empty string"; 
} 
+2

選項3不是一個好的設計決策。它不遵守「關注點分離」/「單一責任原則」,從而使得代碼不易重用。 – Amit

+2

選項4.如果這不是您業務邏輯的要求,您可以拋棄'catch'並且根本不捕獲異常(尤其是'Exception')。 – Dennis

+0

@Amit: - 同意,我只是給了一個選項,希望OP會決定在她/他的代碼中選擇哪一個。 –

1

通過問這個問題,你的暗示GetById對如何處理異常不「業務定義」。在這種情況下,它不應該擔心它,只需讓調用方處理業務邏輯確實知道該怎麼做的例外。

例如,如果調用者是用戶要求獲取某些用戶的詳細信息的某個用戶界面啓動的過程,則可能會顯示失敗消息。

1

IMO,您應該在打印堆棧跟蹤後再次拋出異常。我的意思是,如果一個異常被拋出此代碼:

UnitOfWork unitofwork = new UnitOfWork(); 
    var user = unitofwork.UserInfoRepository.GetByID(Userid); 

有可能出錯了Userid。如果該參數是無效的,拋出一個InvalidArgumentException

catch (Exception ex) { 
    // Do something with ex here, probably print the stack trace 
    throw new InvalidArgumentException("There's something wrong with Userid!"); 
} 

雖然這可能會導致您的應用程序崩潰了很多,這是更好地知道哪裏出了問題。

或者,您可以返回特殊值UsersInfo。我會建議null或添加名爲Error的屬性。

public string Error { 
    get; set; 
} 

您可以檢查此字符串是否有錯誤消息。這裏有一個例子:

var info = GetById(10); 
if (info.Error != null) { 
    Console.WriteLine("Oops! Some error occurred when retrieving user info:"); 
    Console.WriteLine(info.Error); 
    // Do some other handling here. 
} 

也可以使ExceptionError呢!

+0

@Seeper謝謝。現在我得到了一些清晰的圖片 –

+0

如果您認爲可以回答您的問題,請考慮通過點擊該節點來接受它! @SrinivasR – Sweeper

1

追趕所有的不throw東西回來就是非常不好的做法例外;想象一下unitofwork.UserInfoRepository已經拋出,比如OutOfMemoryException - 你還想繼續嗎?

public static UsersInfo GetById(int UserId) { 
    // int is a struct, it can't be null 
    // be exact: what's wrong? - "UserId"; why? - it's non-positive 
    if (UserId <= 0) 
     throw new ArgumentOutOfRangeException("UserId", "Non-positive UserId is not allowed"); 

    try { 
     return new UnitOfWork().UserInfoRepository.GetByID(UserId); 
    } 
    catch (SomeDistinctException) { //TODO: put the right exception type here 
     return null; // UserInfo is not found 
    } 
    } 
+0

非常感謝你@Dmitry這就是我期待的:) –