c# - 出现异常时显示消息框

标签 c# winforms exception

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

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

表格:

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

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

最佳答案

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

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

关于c# - 出现异常时显示消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18823668/

相关文章:

c# - 是否可以获取作为 `params object[]` 传递的变量名称?

c# - AZURE:workerrole 中的异步 Run()

c# - 捕获 C# winform 应用程序中的所有异常

c# - 在 aspx 页面中加载一个又一个控件

c# - 如何在 Visual Studio Community 2013 中创建 ASP.NET MVC 5 Web 应用程序?

c# - 使用重叠面板创建选项菜单

c# - 我必须取消订阅所有事件处理程序吗?

c# - 在 OverFlow 的情况下向下滚动 ContextMenu

mysql - BIRT - org.eclipse.birt.data.engine.odaconsumer.OdaDataException : Cannot get the result set metadata

c# - 识别相同 OleDbException 类型的异常