Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Exception catch block

Tags:

c#

catch-block

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?

like image 928
Bala R Avatar asked Mar 17 '11 21:03

Bala R


2 Answers

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)}

like image 89
Gabe Avatar answered Oct 06 '22 19:10

Gabe


catch without arguments will catch non CLS-compliant exceptions, unlike catch (Exception).

like image 28
Joren Avatar answered Oct 06 '22 20:10

Joren