运行时异常在MSVS的内部和外部之间捕获不同

时间:2011-09-29 05:40:13

标签: c# exception

我在调用异常的程序中调用以下函数

public static List<Templates> LoadTemplates()
{
    // ...
    // System.Threading.Thread.CurrentThread.ManagedThreadId == 1 // ID written to log file
    System.IO.Directory.GetFiles("does_not_exist_directory");
    // ...
}

我尝试在默认的Program.cs中捕获异常

try
{
    // System.Threading.Thread.CurrentThread.ManagedThreadId == 1
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
catch (Exception ex)
{
    MessageBox.Show("ERROR CAUGHT");
}
finally { // do clean up }

在MSVS中运行时,异常会按预期捕获。但是,当通过双击输出目录中的.exe运行时,异常会显示在消息对话框中,显示

编辑:

要从输出目录运行.exe时捕获错误,必须使用处理Application.ThreadException事件编译代码

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form());

但是,通过显示MSVS本机“疑难解答提示”无边框消息对话框“未处理的例外”,MSVS将表现不佳。

如何确保其在MSVS内外的行为相同?

3 个答案:

答案 0 :(得分:4)

您显示的代码仅捕获同一线程中的异常。如果没有看到有问题的代码及其背景,那真的很难说。

您可以订阅几个活动来捕捉所有这些:

请阅读/记录文档(第一个应该做的) - 有一些警告。

答案 1 :(得分:0)

看起来你的LoadTemplates调用是在一个自己的Thread中进行的。我假设您没有在调试模式下看到MessageBox。您将看到Visual Studio异常窗口。

要解决此问题,请尝试使用AppDomain.CurrentDomain.UnhandledException事件:

[STAThread]
static void Main() {
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
    MessageBox.Show("Unhandled exception");
}

答案 2 :(得分:0)

与MSVS内外的异常行为有关,Carsten指出MSDN中的代码是正确的,但是我帮助我更好地了解情况。

(可能是其他情况,但是)当MSVS从MSVS内部运行并且该处理程序在应用程序中的处理程序之前运行时,似乎MSVS将其内部事件处理程序挂钩到应用程序。因此,当发生未处理的异常时,MSVS将显示其本机“疑难解答提示”对话框,指向错误行。

此时,如果我单击继续(F5)继续执行代码,MSVS将重新抛出异常,这次它将由我自己的处理程序捕获。

在MSVS之外,没有其他处理程序被订阅,所以它只是直接运行我的处理程序。

相关问题