Code Emitting try/catch blocks
January 17, 2008 2:01 pm .NetDuring the development of the WCF Client Proxy I had to code emit several try/catch blocks and even if the code looks trivial I still had to rely on a bit of searching to figure it out.
For my own reference (so I know where to come and copy & paste from) here is the code to try/catch:
// Optional: If you need a return value declare your return value iLGenerator.DeclareLocal( typeof(string) ); // string MyMethod( .. ) // try { Label tryLabel = iLGenerator.BeginExceptionBlock(); { // Do you call inside the try/catch block // Optional: if you have a return value save your result in the return value iLGenerator.Emit(OpCodes.Stloc_0); } // catch { - catch everything! { iLGenerator.BeginCatchBlock(typeof(object)); iLGenerator.Emit(OpCodes.Pop); // get the exception from the stack // Maybe do something with the exception // or re-throw; iLGenerator.Emit(OpCodes.Rethrow); } // } iLGenerator.EndExceptionBlock(); // done the try catch // Optional: return returnValue; iLGenerator.Emit(OpCodes.Ldloc_0); // Thanks, all done iLGenerator.Emit(OpCodes.Ret);
The catch is a generic catch all, good if you need to do stuff like sanitize exceptions or log them and then rethrow.