Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

How is that possible? Why is the catch block not working?

like image 267
Oleg Vazhnev Avatar asked Nov 01 '25 14:11

Oleg Vazhnev


2 Answers

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. 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. And by the way you could configure VS not to show them.

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.

like image 184
Darin Dimitrov Avatar answered Nov 04 '25 07:11

Darin Dimitrov


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.

like image 29
500 - Internal Server Error Avatar answered Nov 04 '25 06:11

500 - Internal Server Error