Course contentsShow
← JavaScript
Lesson 1129 of 2,72326. Error HandlingFree lesson

Basic Try/Catch Syntax

Writing your first try/catch block to handle potential runtime errors safely.

Basic Try/Catch Syntax

You'll learn how to write your first try/catch block to safely handle runtime errors and prevent your program from crashing.

Understanding Try/Catch

Think of a try/catch block like a safety net under a trapeze artist. The trapeze artist (your code) attempts their routine inside the "try" section. If they fall (an error occurs), the safety net (the "catch" block) catches them, preventing disaster and allowing the show to continue.

In JavaScript, errors can happen at runtime—maybe you try to access a property on null, parse invalid JSON, or call a function that doesn't exist. Without try/catch, these errors crash your program. With try/catch, you control what happens when things go wrong.

The Basic Syntax

try {
  // Code that might throw an error
  const result = riskyOperation();
  console.log(result);
} catch (error) {
  // Code that runs if an error occurs
  console.log("Something went wrong:", error.message);
}

console.log("Program continues running");

The try block contains code that might fail. If an error occurs anywhere inside the try block, JavaScript immediately jumps to the catch block, skipping any remaining code in try. The catch block receives the error object, which contains information about what went wrong. After the catch block completes, your program continues normally—it doesn't crash.

A Real Example

try {
  const data = JSON.parse('{ invalid json }');
  console.log(data);
} catch (error) {
  console.log("Failed to parse JSON:", error.message);
}

console.log("Still running!"); // This executes

Without try/catch, the invalid JSON would crash your program. With it, you handle the error gracefully and continue.

Key Takeaway: Try/catch blocks let you attempt risky code in the try section and safely handle any errors in the catch section, preventing crashes and maintaining program flow.