admin wrote: ↑Sat Jul 07, 2018 9:00 am
__JJ__ wrote: ↑Sat Jul 07, 2018 7:19 am
Very interesting. This seems like effectively a forward goto. I have found that you don't even need a loop, or if statement to break to an outer label. You can just...do it.
Not really. You can't use break just about anywhere. You need an enclosing loop block to break out of. (or a switch block).
Yes that's what I thought would be the case. But I did check this out before I posted. This is what I had knocked up to get an understanding of how far it might be taken:
Code: Select all
package oca8.practice;
class T7{
public static void main(String args[]){
int i = 0;
OUTER1: {
OUTER2:{
OUTER3:
OUTER4:
INNER:
{
System.out.println("Before try...");
try{
break OUTER1;
} catch(Exception e){
System.out.println("Exception in loop.");
} finally{
System.out.println("In Finally");
}
}
System.out.println("AFTER INNER");
} System.out.println("AFTER OUTER2");
} System.out.println("AFTER OUTER1");
}
}
OUTPUT:
Code: Select all
Before try...
In Finally
AFTER OUTER1
There is no loop, no conditional (if/else), just a try block.
What's interesting is I just tried it without the try block
Code: Select all
package oca8.practice;
class T7A{
public static void main(String args[]){
int i = 0;
OUTER1: {
OUTER2:{
OUTER3:
OUTER4:
INNER:
{
System.out.println("Before try...");
break OUTER1;
}
System.out.println("AFTER INNER"); //error: unreachable statement
} System.out.println("AFTER OUTER2");
} System.out.println("AFTER OUTER1");
}
}
It fails compilation, with unreachable statement, which suggests a try block is seen as a pseudo-conditional, and may (almost certainly does) explain why the answer to one of the other questions (a while(true) inside a try block) was not "compilation fails with unreachable code".