JavaScript•Error Handling
JavaScript Exception Handling: try, catch, finally & throw
Learn structured exception handling in JavaScript, inspecting Error properties (name, message, stack), and cleanup blocks.
Syntax
try {
// risky code
} catch (err) {
// handle err
} finally {
// cleanup
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| try | Block | Monitors enclosed statements for errors. |
| catch (err) | Handler | Catches and processes thrown Error. |
| finally | Block | Always runs after try/catch regardless of success. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// Robust JSON Parsing and Error Handling
function parseUserData(jsonString) {
console.log("Parsing payload...");
try {
const data = JSON.parse(jsonString);
if (!data.username) {
throw new Error("Missing required field 'username'");
}
console.log("Successfully parsed user:", data.username);
return data;
} catch (error) {
console.log("Handling error: [" + error.name + "] " + error.message);
return null;
} finally {
console.log("[Cleanup] Parser finished execution.");
}
}
// 1. Valid JSON test
parseUserData('{"username": "dev_alex", "id": 101}');
// 2. Malformed JSON test
console.log();
parseUserData('invalid json string');Expected Output:
Parsing payload... Successfully parsed user: dev_alex [Cleanup] Parser finished execution. Parsing payload... Handling error: [SyntaxError] Unexpected token 'i', "invalid json string" is not valid JSON [Cleanup] Parser finished execution.
How It Works: Step-by-Step
- Lines 4-9: Tries JSON.parse and validates mandatory fields with throw new Error().
- Lines 10-13: Catches SyntaxError or custom validation errors.
- Lines 14-16: finally block runs unconditionally for cleanup.
Key Concepts
- throw new Error("msg") creates a standard Error with stack trace information.
- Errors not caught in try/catch bubble up to uncaught exception handlers.
- finally executes even if a return statement is present inside try or catch.
Common Mistake: Throwing primitive strings instead of Error objects
Throwing strings like throw "Error" loses stack trace diagnostics. Always throw new Error("msg").
❌ Incorrect
throw "Something went wrong"; // No stack trace!
✅ Correct
throw new Error("Something went wrong"); // Includes file and line stack traceRelated JavaScript Tutorials & Compiler
JavaScript Async/Await, Promises, and Promise.all
Master asynchronous JavaScript using Promises, async/await syntax, and parallel Promise.all.
JavaScript Classes (ES6): Constructors, Methods & Private Fields
Learn Object-Oriented Programming in JavaScript with class syntax, constructor, and private #fields.
JavaScript Functions: Arrow Functions, Parameters, and Rest
Master function declarations, expressions, arrow functions, and rest parameters (...args).
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.