- Home
- Interview Questions
- JavaScript
- How do try, catch and finally work, and what happens if fina…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: The try block runs first. If it throws, control jumps to catch, and finally always runs afterwards, even if try or catch returned or threw. A return inside finally overrides any earlier return or thrown error, which can silently swallow exceptions.
Detailed explanation
A try statement has three parts. You need at least one of catch or finally.
- try holds the code that might throw. If no error occurs,
catchis skipped. - catch (err) runs only when something inside
trythrows. The thrown value, usually anErrorobject, is bound toerr. Since ES2019 you can leave out the binding:catch { ... }. - finally runs in every case: after a normal finish, after
catchhandles an error, after areturn,breakorcontinueinsidetry, and even whencatchitself throws. People use it for cleanup, such as closing a file handle, releasing a lock or hiding a loading spinner.
The tricky part is how finally deals with completion values. When try or catch reaches a return, the engine first evaluates the return expression and stores it. Then it runs finally, and only after that does the function actually return. This has three consequences:
- If
finallyhas noreturnorthrow, the stored value or error goes ahead unchanged. - If
finallyrunsreturn, that value replaces the stored one. If an error was on its way out, the error is discarded completely. - If
finallythrows, the new error replaces whatever was pending.
Because the return value is evaluated before finally runs, reassigning a primitive variable inside finally does not change what gets returned. Mutating an object that was returned by reference does show up, because the caller receives that same object.
Also remember that try...catch only catches errors thrown synchronously while the try block is running. The one exception is an await inside an async function, where a rejected promise is rethrown at that point.
Example
function basic() {
try {
return 'from try';
} finally {
console.log('finally runs');
}
}
basic(); // logs 'finally runs', returns 'from try'
function override() {
try {
throw new Error('boom');
} catch (e) {
return 'from catch';
} finally {
return 'from finally';
}
}
override(); // 'from finally'
function swallow() {
try {
throw new Error('this error is lost');
} finally {
return 'ok';
}
}
swallow(); // 'ok' with no error, the exception vanished
function evaluatedEarly() {
let x = 1;
try {
return x;
} finally {
x = 2;
}
}
evaluatedEarly(); // 1, not 2
// Typical real use: cleanup
async function loadData() {
showSpinner();
try {
const res = await fetch('/api/data');
return await res.json();
} catch (err) {
console.error('Load failed', err);
return null;
} finally {
hideSpinner(); // runs on success and on failure
}
}Common mistakes
- Putting a
returninfinally. It hides real bugs because thrown errors vanish without any trace. Many linters flag this, for example ESLint'sno-unsafe-finallyrule. - Thinking
finallyis skipped whentryreturns. It always runs before control leaves the block. - Writing an empty
catch {}that swallows errors. At minimum, log the error or rethrow it if you cannot actually handle it. - Wrapping a callback-based or non-awaited async call in
tryand expecting its errors to be caught there.
Follow-up questions
- What happens if the catch block itself throws an error?
- When would you rethrow an error from catch instead of handling it?
- How would you check whether a caught value is an Error object or something else?
Interview tip: Show the swallowed-error example where finally returns 'ok'. It proves you understand completion values, not just the basic syntax.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More easy JavaScript questions
Related Questions
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · JavaScript · 1 ans
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)