Is .NET finally equivalent to try-catch-throw?

I am writing a static analysis tool for CIL. Control flow analysis would be simplified if the final blocks could be interpreted as try-catch blocks with a retron inside the catch. In C # I don't see the difference between

try { // ... } finally { // finally code here } 

and

 try { // ... } catch { // finally code here throw; } 

or between

 try { // ... } catch(Exception e) { // catch code here } finally { // finally code here } 

and

 try { try { // ... } catch (Exception e) { // catch code here } } catch { // finally code here throw; } 

In CIL there are even final teams and final teams. There must be a difference, is there?

+4
source share
2 answers

No - the finally block is executed even if an exception is not thrown, and also if another catch detects an exception. (This is true if the catch then throws the exception itself or not.)

Oh, and the finally block will also be executed if the try block is returned from the method.

Basically, if you want the code to always be executed when the statement leaves the statement, finally is what you want. Although in C # I find that I rarely write an explicit finally block, the using statement almost always makes the code simpler.

+14
source

To add to Jon - correctly, of course, answer: you are actually describing a try-fault block. That is, the try-fault block is equivalent to try , followed by a catch total and automatic return.

C # does not support try-fault blocks, but CIL does, so if you ever read IL and see a fault block, now you know what it is.

It’s also correct to say that

 try{} catch {} finally {} 

equivalently

 try { try { } catch { } } finally { } 

And actually inside the C # compiler what it does; all try-catch-finally blocks are overwritten into a nested try-catch inside try-finally. This is a simplifying assumption that can help when writing a static analyzer.

+13
source

Source: https://habr.com/ru/post/1480219/


All Articles