c# - 从 IDE 调试项目但在 IDE 外部运行时未捕获异常

标签 c# .net winforms exception

在 C#、WinForms、VS2008、.NET 3.5 中...

对于这段代码:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {

        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormThatDividesByZero());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
}

public partial class FormThatDividesByZero : Form
{
    public FormThatDividesByZero()
    {
        InitializeComponent();
    }

    private void DivideByZeroButton_Click(object sender, EventArgs e)
    {
        // Create a divide by zero exception.
        int a = 0;
        int b = 0;
        int c = a / b;
    }
}

完整来源:http://forgefx.com/posts/ExceptionReporting.zip

当我在开发环境中通过 F5 运行这个小测试项目时,捕获了单击 DivideByZero 按钮后的异常并触发了消息框。双击/bin/Debug文件夹下的.exe运行工程,没有捕获到异常,也没有消息框,这是为什么?

当从 IDE 外部启动 .exe 时,或从 visual studio 中使用“调试 > 不调试开始”时,我得到一个未处理的异常。我的理解是上面的代码会捕获所有异常。

最佳答案

这不是捕获全局异常的好方法。您可以使用 AppDomain 或 Application 对象来捕获它。此对象捕获所有未处理的异常和调用事件。

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormThatDividesByZero());            

    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Exception ex = (Exception)e.ExceptionObject;
        MessageDialog.Show(ex.Message);
        Application.Exit();
    }

    void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageDialog.Show(e.Exception.Message);
    }
}



public partial class FormThatDividesByZero : Form
{
    public FormThatDividesByZero()
    {
        InitializeComponent();
    }

    private void DivideByZeroButton_Click(object sender, EventArgs e)
    {
        // Create a divide by zero exception.
        int a = 0;
        int b = 0;
        int c = a / b;
    }
}

关于c# - 从 IDE 调试项目但在 IDE 外部运行时未捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147224/

相关文章:

C# 双重加法 - 奇怪的行为

c# - 如何从命令行并行运行 NUnit 测试?

c# - 如何创建用于检查特定时间范围的正则表达式

c# - 在 fluentribbon 按钮中设置 xaml 图标

c# - 简单登录的 MVC 模式中组件的职责是什么

c# - 如何 : SQLite with EntityFramework and Code-First

Java 客户端连接到 SignalR?

c# - "Microsoft.ACE.OLEDB.12.0” 在 Windows 10 中无法识别

c# - Visual Studio 2010 设计器生成无效代码

c# - 循环遍历 Awesomium JSObject