如果发生异常,请显示消息框

Dan*_*ger 8 c# exception winforms

我想知道将一个异常从一个方法传递给我的表单的正确方法是什么.

public void test()
{
    try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception)
    {
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

形成:

try
{
    test();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

这样我就看不到我的文本框了.

Avi*_*ner 16

如果您只想使用异常的摘要:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
Run Code Online (Sandbox Code Playgroud)

如果要查看整个堆栈跟踪(通常更适合调试),请使用:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

我有时使用的另一种方法是:

    private DoSomthing(int arg1, int arg2, out string errorMessage)
    {
         int result ;
        errorMessage = String.Empty;
        try 
        {           
            //do stuff
            int result = 42;
        }
        catch (Exception ex)
        {

            errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
            result = -1;
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

在您的表单中,您将拥有以下内容:

    string ErrorMessage;
    int result = DoSomthing(1, 2, out ErrorMessage);
    if (!String.IsNullOrEmpty(ErrorMessage))
    {
        MessageBox.Show(ErrorMessage);
    }
Run Code Online (Sandbox Code Playgroud)

  • @Dialecticus问题是关于"正确的方法".以上只是建议. (2认同)