What's the difference between the following catch blocks?
try
{
...
}
catch
{
...
}
and
try
{
...
}
catch(Exception)
{
...
}
I realize, in either case, the exception instance is not available but is there anything that I can do with one that is not possible with the other?
They are almost the same.
From the C# Language Specification, section 8.10:
Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code. A general catch clause may be used to catch such exceptions. Thus, a general catch clause is semantically different from one that specifies the type System.Exception, in that the former may also catch exceptions from other languages.
Note that while C# differentiates between the two, they are effectively the same as of .NET 2.0, as noted by this blog:
Thanks to a recent change in the 2.0 CLR, if you had code that decided to throw, say, an int (System.Int32) somewhere, the CLR will now wrap it with a RuntimeWrappedException, and the compiler has been updated to give you that warning that the second clause above is now dead code
warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException
For how the CLR knows to do this action for your assembly, you'll notice the compiler now adds a RuntimeCompatibilityAttribute to your assemblies telling it to:
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = {property bool 'WrapNonExceptionThrows' = bool(true)}
catch
without arguments will catch non CLS-compliant exceptions, unlike catch (Exception)
.
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