Index

Error Handling and Debugging

JavaScript for Beginners

12.1 Types of Errors (Syntax vs Runtime)

When writing JavaScript, errors are inevitable, especially as you learn. Understanding the two main types of errors — syntax errors and runtime errors — helps you quickly identify and fix problems in your code.

Syntax Errors

Syntax errors happen when your code violates the rules of JavaScript’s language structure. They are like grammar mistakes in a sentence.

let x = 10  // Missing semicolon (optional but good practice)
let y = ;   // Syntax error: unexpected token ";"
function() { console.log("Hi") }  // Missing function name

Browsers catch syntax errors before running the code, so the script won’t execute until you fix them. The browser’s developer console usually shows a clear message pointing to the line with the syntax error, like “Unexpected token” or “Missing )”.

Runtime Errors

Runtime errors occur when your code is syntactically correct but something goes wrong while the program runs.

let num = 10;
console.log(num.toUpperCase()); // Runtime error: toUpperCase is not a function

let obj = null;
console.log(obj.name);           // Runtime error: Cannot read property 'name' of null

Unlike syntax errors, runtime errors occur during execution, which means your script starts but then crashes or behaves unexpectedly. Browsers report runtime errors with messages like “TypeError”, “ReferenceError”, or “RangeError” in the console.

Common Beginner Mistakes

How to Identify Errors

Knowing the difference between syntax and runtime errors is the first step to effective debugging and writing robust JavaScript code!

Index

12.2 Using try, catch, finally

In JavaScript, error handling is crucial for building resilient applications that don't crash unexpectedly. The try, catch, and finally blocks allow you to run code safely and handle errors gracefully when they occur.

The try Block

The try block contains the code that might throw an error during execution. If an error occurs inside try, the normal program flow stops and control moves to the catch block.

try {
  // Code that may cause an error
  let result = riskyOperation();
  console.log(result);
}

The catch Block

The catch block catches the error thrown in the try block and allows you to handle it without crashing your program.

try {
  let data = JSON.parse('invalid JSON string');
} catch (error) {
  console.error('Parsing failed:', error.message);
}

Here, instead of the script crashing on invalid JSON, the error is caught and logged.

The finally Block

The finally block runs after the try and catch blocks, regardless of whether an error occurred or not. Use it for cleanup actions like closing files or releasing resources.

try {
  console.log('Trying something risky...');
  // Code that may throw
} catch (error) {
  console.error('Caught an error:', error);
} finally {
  console.log('This always runs, no matter what.');
}

Complete Example: Safe Division

function safeDivide(a, b) {
  try {
    if (b === 0) {
      throw new Error('Cannot divide by zero');
    }
    return a / b;
  } catch (error) {
    console.error('Error:', error.message);
    return null; // Graceful fallback
  } finally {
    console.log('Division attempt finished');
  }
}

console.log(safeDivide(10, 2)); // Outputs: 5
console.log(safeDivide(10, 0)); // Logs error and outputs: null

When to Use try, catch, finally

By using try, catch, and finally, you can make your JavaScript programs more robust, user-friendly, and easier to debug.

Index

12.3 The throw Statement

In JavaScript, you can manually trigger errors using the throw statement. This is useful for signaling exceptional situations in your code that require special handling or to stop execution when something goes wrong.

How throw Works

The throw statement lets you generate an error of any type, but typically you throw an Error object or one of its subclasses (like TypeError, RangeError). When an error is thrown, the normal flow of the program immediately stops and control jumps to the nearest catch block (if one exists).

Syntax:

throw expression;

Example: Throwing a Custom Error

You can create meaningful errors with clear messages to help debugging and communicate problems:

function checkAge(age) {
  if (age < 18) {
    throw new Error('User must be at least 18 years old.');
  }
  return 'Access granted';
}

try {
  console.log(checkAge(16));
} catch (error) {
  console.error('Error:', error.message);
}

Here, throw creates a new error that stops execution if the age is less than 18. The catch block then handles it gracefully.

Throwing Different Error Types

JavaScript has built-in error types you can use for more specific error handling:

throw new TypeError('Expected a number but got a string');
throw new RangeError('Value out of allowed range');

Using specific error types improves clarity when debugging or logging errors.

Why Use throw?

Best Practices for throw

Manually throwing errors with throw empowers you to write safer, more predictable JavaScript by explicitly managing when and how your program handles problems.

Index

12.4 Debugging with Developer Tools

Debugging is an essential skill for every JavaScript developer. Modern browsers like Chrome and Firefox come with powerful Developer Tools that help you find and fix issues in your code efficiently. Here’s a hands-on guide to get you started with debugging.

Opening Developer Tools

This opens a panel with multiple tabs like Elements, Console, Sources (Chrome) or Debugger (Firefox).

Viewing Console Errors

The Console tab shows errors, warnings, and logs:

Setting Breakpoints

Breakpoints pause code execution at a specific line so you can inspect the program’s state.

  1. Open the Sources (Chrome) or Debugger (Firefox) tab.
  2. Navigate to your JavaScript file in the file explorer.
  3. Click the line number where you want to pause.

The code will stop when it reaches this line during execution.

Inspecting Variables

When paused on a breakpoint:

Stepping Through Code

Use the controls to move through your code step-by-step:

Example: Debugging a Function

Suppose you have this code:

function add(a, b) {
  return a + b;
}

let result = add(5, '3');
console.log(result); // Outputs "53" instead of 8

Tips for Effective Debugging

Mastering Developer Tools gives you powerful insight into your JavaScript code, helping you find bugs faster and write better software!

Index