finally in a try/catch statements really goes over everything
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
Today I woke up checked Slack and saw a little trick question by my friend Tomasz in one of the JavaScript channels.
function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f(); // ?
I don't use the finally
block in try/catch
statements very often so I was not sure what the return value will be for this snippet. It turns out the finally
block goes over everything according to MDN:
If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks.
So let's have a look at a few examples:
function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f(); // 'B'
// ***********************************************
function g() {
try {
throw new Error( 'Foo' );
} catch( e ) {
return 'A';
} finally {
return 'B';
}
}
g(); // 'B'
// ***********************************************
function h() {
try {
throw new Error( 'Foo' );
} finally {
return 'B';
}
}
h(); // 'B' (without throwing an exception)
// ***********************************************
function i() {
try {
throw new Error( 'Foo' );
} catch( e ) {
throw new Error( 'Bar' );
return 'A';
} finally {
return 'B';
}
}
i(); // 'B' (without throwing an exception)
finally
overwrites return
statements and also "catches" exceptions. Good to know. ;)
Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 18 days ago.
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 18 days ago.