try...catch...finally & Custom ErrorsJavaScript handles runtime errors using the try...catch...finally exception handling mechanism. When an error occurs, JavaScript throws an Error instance that can be caught, handled, or re-thrown.
flowchart TD
TryBlock["try { ... } Block"] --> CheckErr{"Error Occurs?"}
CheckErr -- "No Error" --> FinallyBlock
CheckErr -- "Error Thrown" --> CatchBlock["catch (error) { ... } Block"] --> FinallyBlock["finally { ... } Block (Always Executes)"]
FinallyBlock --> ExitFlow["Continue Normal Execution"]
| Error Class | Trigger Cause | Example Cause |
|---|---|---|
TypeError |
Invalid operand or type mismatch. | Calling a non-function null.foo(). |
ReferenceError |
Accessing an undeclared variable. | Accessing variable in TDZ or missing identifier. |
SyntaxError |
Invalid JavaScript code syntax. | Parsing invalid JSON JSON.parse("{bad}"). |
RangeError |
Numeric value outside valid range. | Setting array length to negative [].length = -1. |
// Demonstrating try...catch...finally, custom Error classes, and error handling
// Custom Domain Error Class
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function parseUserData(jsonString) {
try {
console.log("Attempting JSON parse...");
const user = JSON.parse(jsonString);
if (!user.email) {
throw new ValidationError("Email field is required.", "email");
}
return user;
} catch (error) {
if (error instanceof SyntaxError) {
console.error(`Syntax Error: Invalid JSON payload -> ${error.message}`);
} else if (error instanceof ValidationError) {
console.error(`Validation Failed on [${error.field}]: ${error.message}`);
} else {
console.error(`Unexpected System Error: ${error.message}`);
throw error; // Re-throw unhandled errors
}
return null;
} finally {
console.log("Cleanup: Parsing operation complete.");
}
}
// Execution test
parseUserData('{"name": "Alex"}'); // Triggers ValidationError
finally for Resource Cleanup: Place cleanup operations (closing file handles, stopping loaders, clearing timers) inside finally blocks to guarantee execution regardless of success or failure.Error: Extend the built-in Error class when creating custom application error types to preserve stack traces.catch (e) {} blocks; at minimum, log errors or report them to monitoring services.What is the output order of console.log statements inside try, catch, and finally when an error is thrown in try?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.