Why continue statement cannot be used inside finally block?

As we are aware that we can use continue statement inside a try or catch block, but not inside finally block. This post explores why continue statement cannot be present inside finally block.

Now for our understanding  let’s assume that we can write continue statements inside finally block also (in reality we get a compile timer error if we write inside finally).

Hence continue statements will be present in both Try block as well as Finally block.

Analysis - The code execution comes to try block and encounters the continue statement, the continue statement will be registered and all the remaining code in try block has to be skipped and control has to pass to the next iteration but since finally block is present, the code execution has to compulsorily pass to finally block.

Now the execution again encounters continue statement present inside the finally block, this will cause ambiguity to the execution, since two continue statements needs to be registered. 


Hence to prevent this ambiguity continue statement cannot be present inside the finally block and can be present in Try or Catch block or both.

Lets look into a example, for better understanding of working of continue statement inside a try or catch block with finally block .
Here, an integer array of size 4 is initialized,
The program throws an exception when the array index is 3 due to the if condition written inside the try block and this exception will be caught by catch block.

Progam Image File

 Output -
Above Program Output


Explanation Here execution is normal till the value is not equal to 3. But when the value is 3 the if condition present inside if statement is satisfied and an exception is thrown and control is passed to the catch block.
Hence During Exception i.e. when array value is 3,the statement Console.WriteLine ("Outside Try/Catch/Finally block"); will not be executed since exception has occurred and control has passed to Catch block due to the presence of  continue statement and then to finally block and then to the next iteration. 
Since continue is present inside catch block the statement Console.WriteLine ("Outside Try/Catch/Finally block") will be not be executed when there is an exception.

In case If continue is not present inside the catch block the statement Console.WriteLine ("Outside Try/Catch/Finally block"); will be executed even when there is an exception. 

Note - Whenever, continue is encountered in a catch/try block control will be passed to finally block, after execution of the code in finally block the control is passed to the next iteration skipping any further lines of code.