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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With