This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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. ;)
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2017-03-07T11:00:00+00:00) finally in a try/catch statements really goes over everything (#tilPost). Retrieved from https://www.scien.cx/2017/03/07/finally-in-a-try-catch-statements-really-goes-over-everything-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.