Search code examples
c#cil

Falling into a catch clause in CIL


For a try block in CIL, I'm aware that you can enter a catch handler by throwing an exception in the protected block such as:

try {
     newobj Exception
     throw
     leave EX1
} catch {
     pop
     ldstr "catchblock"
     call WriteLine
} finally {
     ldstr "finallyblock"
     call WriteLine
}

EX1: 

the throw statement will transfer control to the catch clause, which pops off the exception.

My concern(/curiosity) is whether this could be optimized so execution goes to the catch block not through a throw, but by "falling" into it via increment the PC. Something like this:

try {
     newobj Exception
} catch {
     pop
     ldstr "catchblock"
     call WriteLine
} finally {
     ldstr "finallyblock"
     call WriteLine
}

EX1: 

Is this valid CIL? Is it possible to get to a catch handler block without using a throw statement?


Solution

  • Nope, it's explicitly invalid.

    In ECMA-335 Partition I, Section 12.4.2.8.1:

    Entry to filters or handlers can only be accomplished through the CLI exception system; that is, it is not valid for control to fall through into such blocks. This means filters and handlers cannot appear at the beginning of a method, or immediately following any instruction that can cause control flow to fall through.