Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a 'continue' statement be inside a 'finally' block?

Tags:

c#

.net

I don't have a problem; I'm just curious. Imagine the following scenario:

foreach (var foo in list) {     try     {          //Some code     }     catch (Exception)     {         //Some more code     }     finally     {         continue;     } } 

This won't compile, as it raises compiler error CS0157:

Control cannot leave the body of a finally clause

Why?

like image 430
lpaloub Avatar asked Aug 01 '13 10:08

lpaloub


People also ask

What happens if there is an exception inside finally block?

The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.

Does finally execute after continue Python?

The finally statement is always executed no matter what.

Does finally {} block always run?

A finally block always executes, regardless of whether an exception is thrown.

Can we keep other statements in between try catch and finally blocks?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.


1 Answers

finally blocks run whether an exception is thrown or not. If an exception is thrown, what the heck would continue do? You cannot continue execution of the loop, because an uncaught exception will transfer control to another function.

Even if no exception is thrown, finally will run when other control transfer statements inside the try/catch block run, like a return, for example, which brings the same problem.

In short, with the semantics of finally it doesn't make sense to allow transferring control from inside a finally block to the outside of it.

Supporting this with some alternative semantics would be more confusing than helpful, since there are simple workarounds that make the intended behaviour way clearer. So you get an error, and are forced to think properly about your problem. It's the general "throw you into the pit of success" idea that goes on in C#.

C#, you, and the out if success

If you want to ignore exceptions (more often than not is a bad idea) and continue executing the loop, use a catch all block:

foreach ( var in list ) {     try{         //some code     }catch{         continue;     } } 

If you want to continue only when no uncaught exceptions are thrown, just put continue outside the try-block.

like image 121
R. Martinho Fernandes Avatar answered Oct 19 '22 19:10

R. Martinho Fernandes