在异常情况下显示消息框

11

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

public void test()
{
    try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception)
    {
        throw;
    }
}

表格:

try
{
    test();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

以这种方式,我无法看到我的文本框。


8
test 方法中的 try/catch 是多余的。 - Hamlet Hakobyan
1
exceptions 向上传递到调用链。 - Sam Leach
4
我看不到任何问题。消息框应该会弹出。发生了什么? - Sriram Sakthivel
你应该能够看到消息框。如果你用MessageBox.Show("Hi")替换try-test-catch-messagebox,会发生什么? - Dialecticus
可能是重复的问题:http://stackoverflow.com/questions/12347531/using-messagebox-to-show-exception-information-in-multithreaded-application - goamn
3个回答

23

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

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

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

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

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

    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;
    }

在您的表单中,您将会有类似以下的内容:

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

1
不需要更改原始OP的代码,因为原始代码应该可以正常工作。问题出在其他地方。 - Dialecticus
2
@Dialecticus 这个问题是关于“正确的方式”的。上面只是建议。 - Avi Turner
1
我想说的是,你正在试图解决一个不存在的问题。或者更糟糕的是,你正在回答一个不存在的问题。 - Dialecticus
1
我认为用户的问题是消息框遮挡了文本框。"这样我就看不到我的文本框了",而且没有人回答这个(更加复杂)的问题。 - Derek Johnson

1
有很多方法,例如:

Method one:


public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

方法二:
public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

不需要更改原始OP的代码,因为原始代码应该可以正常工作。问题出在其他地方。 - Dialecticus

0
        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

4
我认为如果您在帖子下方添加一些解释(使用编辑链接进行操作),这将对原帖作者和其他访问者更有帮助。 - Reporter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接