2012-05-14 73 views
1

是否可以將參數傳遞給catch塊? 下面是一些示例代碼:捕捉參數?

try 
{   
    myTextBox.Text = "Imagine, that could fail"; 
} 
catch (Exception e) 
{ 
    MessageBox.Show(e.Message); 
} 

我現在可以通過文本框(myTextBox)到我的catch塊,如果它會失敗?不便。像這樣:

try 
{   
    myTextBox.Text = "Imagine, that could fail"; 
} 
catch (Exception e, TextBox textBox) 
{ 
    textBox.BorderBrush = Colors.Red; 
    MessageBox.Show(e.Message); 
} 

我該怎麼做?

回答

5

不,這是不可能的標準。

可以做什麼,是定義你的自定義異常和分配參數有,例如:

public class MyCustomException : Exception 
{ 
    public string SomeAdditionalText {get;set;} 
    .... 
    //any other properties 
    ... 
} 

並拋出一個異常提高自己MyCustomException

1

不要裏面的方法不知道你想實現什麼,但是在catch塊中,你可以像訪問try塊一樣訪問任何UI元素。所以對於我來說,在catch塊中定義一個附加參數沒有意義。

5

你只有catch一件事情,在C#中必須是一個Exception。所以不直接。然而!如果Exception是例如自定義SomethingSpecificException,那麼您可以在e.SomeProperty上提供該信息。

public class SomethingSpecificException : Exception { 
    public Control SomeProperty {get;private set;} 
    public SomethingSpecificException(string message, Control control) 
      : base(message) 
    { 
     SomeProperty = control; 
    } 
    ... 
} 

然後,在某些時候,你可以:

throw new SomethingSpecificException("things went ill", ctrl); 

catch(SomethingSpecificException ex) { 
    var ctrl = ex.SomeProperty; 
    .... 
} 
+0

對於這個問題,這不是有點矯枉過正嗎? =) –

+1

@Mario大多數程序/上下文比單純的10行SO問題更復雜;假設問題是真實事物的簡化版本是合理的。所以:也許,也許不是。 –

+0

也許就是這樣。但我在想,你可能有一個*更容易*解決方案給出的上下文。 –

0

下一步,使用自定義異常分清哪些可能性是怎麼回事:

try 
{ 
    myClass.DoSomethingThatCouldThrow(); 
    myClass.DoSomethingThatThrowsSomethingElse(); 
    myClass.DoAnotherThingWithAThirdExceptionType(); 
} 
catch(FirstSpecialException ex) 
{ 
    // Do something if first fails... 
} 
catch(SecondSpecialException ex) 
{ 
    // Do something if second fails... 
} 

你也可以把每個狀態進入它自己的異常塊。這會使你的代碼很長,但如果你不能改變這個類來拋出任何特殊的異常,這也許是唯一的可能。

try 
{ 
    myClass.DoSomethingThatCouldThrow(); 
} 
catch(InvalidOperationException ex) 
{ 
    // Do something if it fails... 
} 

try 
{ 
    myClass.DoSomethingThatCouldThrow(); 
} 
catch(InvalidOperationException ex) 
{ 
    // Do something if it fails... 
} 

try 
{ 
    myClass.DoAnotherThingWithAThirdExceptionType(); 
} 
catch(InvalidOperationException ex) 
{ 
    // Do something if it fails... 
} 

由於這樣的事實,即這最後的,看起來像重複的代碼一點點,我們也許可以把它放到一些方法具有以下機構:

public void TryCatch<ExceptionT>(Action tryMethod, Action<ExceptionT> catchMethod) 
    where ExceptionT : Exception 
{ 
    // ToDo: ArgumentChecking! 

    try 
    { 
     tryMethod(); 
    } 
    catch(ExceptionT ex) 
    { 
     catchMethod(ex); 
    } 
} 

哪你能不能再與調用:

TryCatch<InvalidOperationException>(
    () => myClass.DoSomething(), 
    (ex) => Console.WriteLine(ex.Message));