+ 2
Does try{}finally{} overwrite variables?
if you try{return 1;}finally{return 2;} why does it return 2?
4 Respostas
+ 6
It seems that Java will execute, no matter what, what is inside block Finally. That means that the value returned will be 2 in that case.
(This is quite illogical for me, tbh)
http://programming.guide/java/try-finally.html
+ 4
I'm not familiar with Java, but my logic tells me the following:
Only the block inside Try {} would be executed in that case, since when returning a value, it immediately leaves the function. In any case, I think that case is not very illustrative and if you really need to do something like that you should reevaluate your code to get a better solution.
Another option is that you get a compilation error, although it is unlikely.
+ 1
Mickel Sánchez
public static int getNum(){
try{
return 1;
}finally{
return 2;
}
public static void main(String[] args){
System.out.println(getNum());
}
//Output:2
//Why?
+ 1
Mickel Sánchez Thanks for the link! That clerified my question.