Monday, December 28, 2009

Statement not reachable : Compilation Error

Scenario 1
try{

while(true) {
// As it goes into infinite loop here, compiler will throw this error here
}
System.out.println("compiler error! statement not reachable");

}

Scenario 2
public static int method(){
try{

return 1;
int i=1;
if(i==2)
i=4;
}

Scenario 3
public static int method(){
try{
throw new Exception();
return 1;
}
catch(Exception e){
return 2;
}
finally{
return 3;
}
}

Scenario 4
Here no compile time errors will be thrown. An exception will be thrown at run time.
Here although method2() will definitely throw the exception, compiler will not recognize this.

public static void main(String args[]) throws Exception {
System.out.println(method());
}
public static int method() throws Exception {
method2();
return 3;
}
public static void method2() throws Exception {
throw new Exception();
}

No comments: