There are three cases to be considered :
Case 1:
public class Test {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
return;
System.out.println(3);
}
}
Case 2:
public class Test {
public static void main(String[] args) {
try{
System.out.println(1);
return;
}finally{
System.out.println(2);
}
System.out.println(3);
}
}
Case 3:
public class Test {
public static void main(String[] args) {
try{
System.out.println(1);
return;
}catch(Exception e){
System.out.println(2);
}
System.out.println(3);
}
}
I understand that in case 1 statement System.out.println(3)
is unreachable that's why it is a compiler error, but why compiler does not shows any error in case 3.
Also note that it is even a compiler error in case 2.
Case 3:
If exception is raised than all your code is available and it prints 1,2,3. That's the reason why you don't have any error (unreachable code) there.
Case 2:
In this case no matter what you won't reach System.out.println(3)
, because you always return from main
method.
In case 2 you have a finally clause. It is executed after the try clause. So the execution order is:
And the "System.out.println(3);" is unreachable.
But in case 3 you have a cath clause. It is executed if there is a Exeption in the try clause. So there are to possible ways to go (with or without error on "System.out.println(1);")
First without error:
Second with error:
PS.: In case 2 if you had a Exception on System.out.println(1); he would run the System.out.println(2); just before continue to throw the exception up to the stack trace...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With