Does try{}finally{} overwrite variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Does try{}finally{} overwrite variables?

if you try{return 1;}finally{return 2;} why does it return 2?

29th Apr 2018, 1:04 AM
Evan Martine
4 Answers
+ 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
29th Apr 2018, 1:43 AM
Mickel
Mickel - avatar
+ 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.
29th Apr 2018, 1:27 AM
Mickel
Mickel - avatar
+ 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?
29th Apr 2018, 1:38 AM
Evan Martine
+ 1
Mickel Sánchez Thanks for the link! That clerified my question.
29th Apr 2018, 1:51 AM
Evan Martine