JS try catch finally
In this page:
The try Block
Code placed inside a try block runs normally until (and unless) it throws; if nothing throws, the catch block is skipped entirely and execution continues after it.
Example: The try Block
try {
console.log("This runs");
} catch (e) {
console.log("Skipped, nothing threw");
}
The catch Block
The catch block receives the thrown value as its parameter and runs only when the try block throws, letting you inspect the error, decide how to respond, and optionally recover instead of letting it propagate further.
Example: The catch Block
try {
null.name;
} catch (error) {
console.log("Caught:", error.message);
}
The finally Block
The finally block runs after try/catch regardless of whether an error was thrown or caught, making it the right place for cleanup code like closing a file or resetting UI state.
Example: The finally Block
try {
console.log("try");
} finally {
console.log("finally always runs");
}
Return with try catch finally
A return inside try is deferred until after finally runs; if finally also returns a value, that finally return silently overrides the one from try — a subtle gotcha worth knowing.
Example: Return with try catch finally
function test() {
try {
return "from try";
} finally {
return "from finally"; // overrides the try's return
}
}
console.log(test());
Nested try catch
try/catch blocks can be nested, letting an inner block handle a specific, recoverable failure while an outer block catches anything more serious that escapes the inner one.
Example: Nested try catch
try {
try {
throw new Error("inner failure");
} catch (inner) {
console.log("Handled inner:", inner.message);
}
} catch (outer) {
console.log("Handled outer:", outer.message);
}
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: