So, in .NET, what you ask is theoretically possible, but it will not be easy.
CIL actually defines five types of exception handling blocks! try , catch and finally ones you used in C #, and two others:
filter - like a catch , but can run arbitrary code to determine if it wants to handle the error, and not just match by type. This block has access to the exception object and has the same effect on the trace of the exception stack as the catch .
fault - It looks like a finally block, but it only starts when an exception occurs. This block does not have access to the exception object and does not affect the trace of the exception stack (like the finally block).
filter is available in some .NET languages (for example, VB.NET, C ++ / CLI), but is not available in C #, unfortunately. However, I do not know any language other than CIL, which allows you to express a fault block.
Because it can be done in IL, but not all is lost. Theoretically, you can use Reflection.Emit to dynamically emit a function with a fault block, and then pass the code you want to run as lambda expressions (i.e. one for the try part, one for the error part, etc.) ), however (a) it’s not easy, and (b) I’m not convinced that this will actually give you a more useful stack trace than you currently get.
Sorry, the answer is not “here how to do it,” but at least now you know! What you are doing now is probably IMHO's best approach.
Pay attention to those who say that the approach used in the question is “bad practice”, in fact this is not so. When you implement the catch , you say: “I need to do something with the exception object when an exception occurs”, and when you implement finally , you say: “I do not need the exception object, but I need to do something to the end functions. "
If what you are actually trying to say is: “I do not need an exception object, but I need to do something when an exception occurs,” then you are halfway between them, i.e. want a fault block. Since this is not available in C #, you do not have an ideal option, so you can also choose an option that is less likely to cause errors, forgetting to flip, and which will not damage the stack trace.