要捕捉的参数?

eMi*_*eMi 1 c# try-catch

是否可以将参数传递给catch块?这是一些示例代码:

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

如果失败,我现在可以将文本框(myTextBox)传递给我的catch块吗?不便.像那样:

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

我该怎么做?

Tig*_*ran 6

不,不可能通过标准来实现.

可以做的是定义自定义异常并在那里分配参数,例如:

public class MyCustomException : Exception
{
    public string SomeAdditionalText {get;set;}
    ....
    //any other properties
    ...
}
Run Code Online (Sandbox Code Playgroud)

并且在引发异常的方法内部引发自己的异常 MyCustomException


Mar*_*ell 6

你只有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;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

那么在某些时候你可以:

throw new SomethingSpecificException("things went ill", ctrl);
Run Code Online (Sandbox Code Playgroud)

catch(SomethingSpecificException ex) {
    var ctrl = ex.SomeProperty;
    ....
}
Run Code Online (Sandbox Code Playgroud)