JavaScript:JavaScript Exception Handling: try, catch, finally & throw
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:

ParameterTypeDescription
tryBlockMonitors enclosed statements for errors.
catch (err)HandlerCatches and processes thrown Error.
finallyBlockAlways runs after try/catch regardless of success.

Ready-to-Run Code Example

Executable in Compilra

Run 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 trace

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler