< go back to home

Try Catch Finally Gotcha

October 13, 2019

I encountered a seemingly simple programming gotcha that I would want to note as a lesson to myself. It is about my misunderstanding on when "return" command kicks-in in a try-catch-finally block. To illustrate, refer to Javascript code below:

I previously expected that the "foo" function would return 1 as it will exit the function before reaching "finally". I was wrong as it returned 3, which means it was able to reach "finally" and would not be able to "return 1".

This is also applicable to the "catch" block as shown below. I expected it will go to "catch" block that would return 2, exitng the foo function and ignoring "finally" block. But simillar to the "try" block, it would proceed to "finally" without being able to "return 2".