Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue is not inside a loop

I was writing a method for TCPServer. I've written a code as below:

    // thread run
protected void threadRun(){
    // continue running. don't stop
    while(true){
        try{
            try{
            }
            catch(Exception e1){
                try{
                } catch(Exception e2){}
                finally{
                    // skip
                    continue;
                }
            }
        }
        catch(Exception e3){
        }
    }
}

Content is not important. There were codes to accept client etc, but I have removed them to make sure about that it is not about details. Anyway, when I try to compile this code, compiler says for that continue line:

Error: continue is not inside a loop

By thinking that maybe I know it wrong, I've written the complete same code in Java as seen below:

class test{
public static void main(String[] args){
    while(true){
        try{
            try{
            }
            catch(Exception e1){
                try{
                } catch(Exception e2){}
                finally{
                    continue;
                }
            }

        }
        catch(Exception e3){
        }
    }
}
}

As I expected, java compiler doesn't give any error message and compiles successfully. What exactly can the problem be?

like image 866
tcak Avatar asked Nov 04 '22 07:11

tcak


1 Answers

Apparently, continue (and break) can't break out of a finally block. Compiling this:

void run() {
loop:
    while (true) {
        try {}
        catch (Exception e) {}
        finally {
            continue loop;
        }
    }
}

will give you this (omitting the label gives the same error you got):

Error: cannot continue out of finally block

I haven't yet found a justification or explanation of this restriction (edit: see ratchet freak's comment below). However, I can't imagine it's a super-common use case. You probably want to look at other options.

like image 96
scry Avatar answered Nov 16 '22 08:11

scry