Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any real-world implications for general catch clause emitting System.Object as type filter?

Tags:

c#

.net

cil

I recall hearing once that throwing an object of some type other than System.Exception (or those extending it) was technically legal CIL, though C# has no feature to support it. So I was interested to see that the following C# code:

try {
    throw new Exception();
} catch(Exception x) {
    try {
        throw;
    } catch {
        Console.Write("yes");
    }
}

compiles to the following CIL:

  .try
  {
    IL_0000:  newobj     instance void [mscorlib]System.Exception::.ctor()
    IL_0005:  throw
  }  // end .try
  catch [mscorlib]System.Exception 
  {
    IL_0006:  pop
    .try
    {
      IL_0007:  rethrow
    }  // end .try
    catch [mscorlib]System.Object 
    {
      IL_0009:  pop
      IL_000a:  ldstr      "yes"
      IL_000f:  call       void [mscorlib]System.Console::Write(string)
      IL_0014:  leave.s    IL_0016
    }  // end handler
    IL_0016:  leave.s    IL_0018
  }  // end handler

where we see that the nested general catch clause compiles to:

catch [mscorlib]System.Object 

in C#, are there any real-world implications for general catch clause emitting System.Object as type filter instead of System.Exception?

like image 671
Stephen Swensen Avatar asked Dec 31 '12 09:12

Stephen Swensen


People also ask

Is catching exception bad practice?

The general principal is to catch the most specific type you can. catch(Exception) is a bad practice because it catches all RuntimeException (unchecked exception) too.

What would be a good reason to use a exception filter?

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.

Is it good to catch generic exception?

So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead. A similar rule here is never throw exceptions of type System. Exception.

What is the usage of try and catch clause in Java?

Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


1 Answers

There is a difference pre .NET-2.0. I read about it in the .NET 1.1 days.

It is explained here (I won't copy it). Note that the first answer is wrong and the second is right.

As to whether it is practical or not: No. I guess it was important for obscure interop scenarios.

like image 173
usr Avatar answered Oct 10 '22 10:10

usr