您好我想問,因爲我不知道,如果它propriete使用異常的:如果聲明爲拋出Exception?
public int Method(int a, int b) {
if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff...
}
我可以拋出異常後if語句?還是應該總是使用try-catch?
您好我想問,因爲我不知道,如果它propriete使用異常的:如果聲明爲拋出Exception?
public int Method(int a, int b) {
if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff...
}
我可以拋出異常後if語句?還是應該總是使用try-catch?
這是完全有效的。這正是異常用於檢查邏輯中的「異常」,而不是假設的事情。
捕捉異常背後的想法是,當您將數據傳遞到某處並處理它時,您可能並不總是知道結果是否有效,即是何時需要捕獲。
關於你的方法,你不想趕內Method
但INFACT當你調用它,這裏有一個例子:
try
{
var a = 10;
var b = 100;
var result = Method(a, b);
}
catch(ArgumentException ex)
{
// Report this back to the user interface in a nice way
}
在上述情況下,是小於b,因此您可以除外在這裏得到一個例外,你可以相應地處理它。
這很好。你是拋出的例外,不捕捉/處理它,所以你不會需要try/catch
塊。
在這種情況下,您不希望發生異常。你扔它提醒來電者,他們以他們稱之爲方法的方式犯了一個錯誤。捕捉它可以防止這種情況發生。所以是的,你的代碼看起來很好。
你在這裏所做的完全正確。
arg檢查的常見模式是將檢查/拋出代碼封裝在靜態「Contract」類中,以確保在驗證輸入參數時具有一致的異常管理方法。
稍微偏離主題,但如果使用.NET 4.0,還可以查看新的Code Contracts功能以驗證方法輸入和輸出。
這是完全有效的,即使使用構造函數也可以使用相同的構造。 但你不應該做是
public int Method(int a, int b)
{
try
{
if (a < b)
throw new ArgumentException("the first argument cannot be less than the second");
}
catch (Exception)
{
}
return 0;
}
你有正確的想法。你可以使用你的代碼是這樣的:
void MyMainMethod()
{
// ... oh, let's call my Method with some arguments
// I'm not sure if it'll work, so best to wrap it in a try catch
try
{
Method(-100, 500);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
public int Method(int a, int b)
{
if (a < b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff ... and return
}
這可能有助於通過MSDN's Handling and Throwing Exceptions和Best Practices for Handling Exceptions
看