【问题标题】:Show message box in case of exception出现异常时显示消息框
【发布时间】:2013-09-20 08:18:35
【问题描述】:

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

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

表格:

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

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

【问题讨论】:

  • test 中的 try/catch 方法是多余的。
  • exceptions 在调用链中冒泡。
  • 我没有看到任何问题。消息框应该弹出。发生了什么事?
  • 您应该可以看到消息框。如果只用MessageBox.Show("Hi") 替换try-test-catch-messagebox 会发生什么?

标签: c# winforms exception


【解决方案1】:

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

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

【讨论】:

  • 原OP的代码不需要修改,原代码应该可以。问题出在其他地方。
  • @Dialectus 问题是关于the correct way。以上只是建议。
  • 我的意思是你正在尝试解决一个不存在的问题。或者更糟的是,您正在回答不存在的问题。
  • 我相信用户的问题是消息框遮挡了文本框。 “以这种方式我看不到我的文本框”并且没有人回答这个(更复杂的}问题。
【解决方案2】:

方法有很多,例如:

方法一:

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的代码无需改动,原代码应该可以工作。问题出在其他地方。
【解决方案3】:
        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

【讨论】:

  • 我认为,当您为您的意图添加一些说明时,这对操作员和其他访问者会更有帮助(使用您帖子下方的编辑链接来执行此操作)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多