即使处理异常IS,在VS2010调试器中获取未处理的异常

Dav*_*ave 8 debugging visual-studio-2010 unhandled-exception

我有一个VS2010的问题,调试器停止时出现Unhandled Exception.但是,例外肯定是处理的.事实上,如果我把代码放在catch块中,当我按下F5时我会点击它.在Debug - > Exceptions中,我绝对没有选中"Thrown"复选框,因此IMO绝对没有理由弹出未处理的异常对话框...

我无法发布确切的代码,但很快就可以处理样本了.违规代码部分背后的基本思想是我有一个与硬件对话的线程,如果我有一个错误与它交谈,那么我抛出一个HardwareException.线程启动BeginInvoke时,我调用时会在回调处理程序中捕获异常EndInvoke.

当在调试器中抛出异常时,我得到一个消息框,上面写着"硬件异常不由用户代码处理".但它是!!!

编辑 - 嗯,这让我发疯了.我有示例代码,代表我在我的应用程序中的代码,它看起来像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace ConsoleApplication1
{
    public class HardwareException : ApplicationException
    {
        public HardwareException( string message) : base(message) {}
    }

    class Program
    {
        delegate void HardwareTestDelegate();

        static void Main(string[] args)
        {
            HardwareTestDelegate d = new HardwareTestDelegate( HardwareTestThread);
            d.BeginInvoke( HardwareTestComplete, null);
            while( true);
        }

        static void HardwareTestThread()
        {
            throw new HardwareException( "this is a test");
        }

        static void HardwareTestComplete( IAsyncResult iar)
        {
            try {
                AsyncResult ar = (AsyncResult)iar;
                HardwareTestDelegate caller = (HardwareTestDelegate)ar.AsyncDelegate;
                caller.EndInvoke( iar);
            } catch( Exception ex) {
                Console.WriteLine( "Should see this line without getting an unhandled exception message in the IDE");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我从线程抛出HardwareException,然后在调用EndInvoke时处理异常.我猜Murphy是对的,因为当我运行这个示例代码时,它会做我所期望的 - 即IDE中没有弹出未处理的异常错误消息!

goo*_*ate 2

以下是微软的回复,案例 111053102422121。Allen Weng写道:

\n\n

分析:

\n\n

供您参考,当您调用 EndInvoke() 时,CLR 将在回调内重新引发异常。下面是 EndInvoke() 的简化版本:

\n\n
public object EndInvoke(IAsyncResult asyncResult)\n{\n    using (new MultithreadSafeCallScope())\n    {\n        ThreadMethodEntry entry = asyncResult as ThreadMethodEntry;\n         ............\n        if (entry.exception != null)\n        {\n            throw entry.exception;\n        }\n     }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果提供了异常处理程序,则异常将在回调函数或异步方法中处理。这就是在没有附加调试器的情况下它的工作方式。

\n\n

当您在 VS.NET 中运行它时,调试器似乎只检查异步方法中是否存在异常处理程序。如果没有这样的处理程序,调试器会认为异常没有被处理,并弹出一条错误消息来通知您。

\n\n

建议:

\n\n

当您单独运行该应用程序时,它应该按预期工作。如果错误消息在调试过程中让您感到烦恼,您可以通过在“异常”对话框中取消选中 \xe2\x80\x9cUser unhandled\xe2\x80\x9d for \xe2\x80\x9cCommon Language Runtime Exceptions\xe2\x80\x9d 来禁用它(调试|异常或按 CTRL+ATL+E)。或者你可以在异步方法中添加try/catch。在后一种情况下,异常被设置为 null,并且不会在 EndInvoke() 中重新引发\xe2\x80\x99。

\n