Reputation: 700
public class ExceptionTest {
public static void throwit(){
throw new RuntimeException();
}
public static void main (String[]args){
try{
System.out.println("Hello");
throwit(); // doesn't compile if this line is replaced with throw new RuntimeException.
System.out.println("Done");
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
System.out.println("Finally");
}
}
}
I was experimenting with try-catch-finally and throwing exceptions and I couldn't figure out why I was getting an error one way while the other way it compiled fine, even though they do the same thing.
I have a method called throwit()
which throw's a new RuntimeException
. I called it under the try block in the main method and everything compiled fine and worked. However if I replaced the throwit();
with just throw new RuntimeException
than the line below that is unreachable.
But, isn't throwit()
and throw new RuntimeException
doing the same thing? throwit()
throws a new RunetimeException
and just saying throw new RuntimeException
does the same thing as well.
So, my question is why does the method which throws a new RuntimeException
compile with no errors while just directly calling throw new RuntimeException
causes an unreachable line, even though they do the exact same thing? If anyone could answer this for me that would be really appreciated.
Upvotes: 2
Views: 966
Reputation: 201477
Because the static code analyser in the Java compiler cannot determine that the line is unreachable when the method is hard-coded to throw the RuntimeException
; whereas, when you hardcode the throws line the compiler can detect that the next statement is unreachable and will not allow you to compile.
JLS-14.21 Unreachable Statements says in part,
The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
Upvotes: 6