10

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

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

形式:

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

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

4

3 回答 3

21

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

    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);
    }
于 2013-09-16T09:25:32.317 回答
1

有很多方法,例如:

方法一:

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;
        }
}
于 2013-09-16T08:50:57.457 回答
0
        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }
于 2014-10-01T08:45:36.053 回答