简体   繁体   English

存在System.ArgumentException的捕获块,但是无论如何都没有捕获到异常,为什么?

[英]Catch block for System.ArgumentException exists, but exception is not caught anyway, why?

I have this code: 我有以下代码:

       if (typeof(Enum).IsAssignableFrom(typeof(T)))
        {
            try
            {
                return (T)Enum.Parse(typeof(T), text);
            }
            catch (ArgumentException e)
            {
                return default(T);
            }
        }

However I received the following exception: 但是,我收到以下异常:

A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Requested value 'ABC' was not found mscorlib.dll中发生类型'System.ArgumentException'的第一次机会异常附加信息:找不到请求的值'ABC'

How is that possible? 那怎么可能? Why is the catch block not working? 为什么catch不灵块?

Why is the catch block not working? 为什么挡块不起作用?

The catch block is working perfectly fine, it's just that you are looking this in Visual Studio debugger. catch块工作得非常好,只是您在Visual Studio调试器中正在寻找它。 That's what a first chance exception means. 这就是第一次机会异常的意思。 When you debug, all exception are shown in VS, it's just that a first chance exception might disappear if you have a proper catch clause. 调试时,所有异常都显示在VS中,只是如果您具有适当的catch子句,则第一次机会异常可能会消失。 And by the way you could configure VS not to show them. 顺便说一下,您可以将VS配置为不显示它们。

Oh and just a side note: in .NET 4.0 there's the Enum.TryParse method so you don't even need to try and catch in this particular snippet. 哦,还有一点需要注意:在.NET 4.0中,有Enum.TryParse方法,因此您甚至不需要try catch这个特定代码段。

A first-chance notification is just to let the debugger know that the exception was thrown - this happens before any catch frames are considered. 优先通知只是让调试器知道引发了异常-这是在考虑任何捕获帧之前发生的。 So in short your exception is (probably) caught. 简而言之,您的异常(可能)被捕获了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM