I was wondering why the following code would be accepted by the Java compiler:
public class Main {
public static void main(String ... args){
System.out.println("a() = " + a());
}
public static String a (){
try {
return "a";
}catch(Throwable t){
}finally{
return "b";
}
}
}
This can and should not work. The java specification states the finally
block will always be executed, but at the same time the return value has already been specified. So either you cannot execute the return "b"
statement, because you have exited at return "a"
, which would be incorrect.
However, the other option is that you execute the return "b"
statement, and thereby totally disregarding the return "a"
statement...
I would say that both are wrong, and I would expect that this does not compile. However it compiles and runs fine. I will leave the answer as a nice exercise to the reader ;).
Basically my question is: Besides being bad practice, would this be considered a Java bug, or does this have other wonderful uses other than obfuscation?
Edit:
The question is not so much if it is a bug, that has been answered, but does it have nice use cases?