Reputation: 6077
If I have the method:
public static boolean getA() throws Exception{
try{
throw new Exception();
}finally
{
}
}
There is no return statement required. Moreover, if we try to add a return statement at the end, it produces the "unreachable statement" error.
Why is this so? Is it certain the the program will not come out of the block, and that the exception will be thrown?
Furthermore, if we add a catch block instead of the finally block, then it requires the return statement to be present there.
Upvotes: 1
Views: 198
Reputation: 13402
Because you have specified an throw statement and there is nothing else in the method definition. That is why. I guess it was that simple.
The return statement will be unreachable, because it is going to throw the exception irrespective of everything.
The catch will require the return statement, because you are handling the exception explicitly now it wants you to return as you have declared in the method definition.
I hope you are aware, you can keep both catch and finally blocks. Because they serve different purpose of their own.
Upvotes: 2
Reputation: 97
It might be because when you throw an exeception, execution stops, hence why finally will never run. When you catch the exception, execution will proceed, and you will have to return.
Upvotes: 0
Reputation: 6371
Yes it is certain that the program will throw an exception, this is the first line of what you're doing in your try block.
Even if it wasn't the first statement in your try block, you don't have a catch block so any other theoretically previously thrown exception would not be caught.
Upvotes: 0