JavaScrip Throw Statements: Tutorial & Examples

Updated: February 19, 2023 By: Khue Post a comment

This practical article shows you how to use throw statements to deal with errors in Javascript.

Overview

In JavaScript, the throw statement is used to throw an exception. When an error occurs in a program, you can use throw to signal that an error has occurred and to stop the execution of the program.

Syntax:

throw expression;

The expression can be any value, but it is typically an object that provides information about the error.

Words might be confusing and not enough to draw the full picture of the throw statement. Let’s see a couple of examples that demonstrate the most common real-world use cases.

Examples

Throwing a string

In the example below, we will define a function named divide that can take 2 arguments. It will check whether the second parameter is zero. If it is the case, the function will throw a string with an error message. If the second parameter is not zero, the function performs the division and returns the result.

The code:

const divide = (a, b) => {
  if (b === 0) {
    throw 'Cannot divide by zero';
  }
  return a / b;
};

console.log(divide(10, 0));

Output:

Error: Cannot divide by zero

Throwing an error object

The code:

const checkAge = (age) => {
    if (age < 18) {
      throw new Error('Must be 18 or older');
    }
    console.log('Access granted');
}
  
checkAge(5);

Output:

Error: Must be 18 or older

Code explained: The checkAge function checks whether the age parameter is less than 18 or not. If it is true, the function will throw an Error object with an error message. If the input is 18 or greater, the function will print Access granted to the console.

Throwing a custom error object

The code:

// Define a custom error class
class InvalidNameError extends Error {
  constructor(message) {
    super(message);
    this.name = 'InvalidNameError';
  }
}

// Use the custom error class
function greet(name) {
  if (!name || name.length < 3) {
    throw new InvalidNameError('Invalid name');
  }
  console.log(`Hello, ${name}!`);
}

greet('D');

Output:

InvalidNameError: Invalid name

Code explained: We define a custom error class named InvalidNameError that extends the built-in Error class. The greet function checks whether the name parameter is null or has a length of less than 3. If it does, the function will throw an instance of the InvalidNameError class with an error message. If the name parameter is valid, the function will write a greeting to the console.

Catching a thrown error

This example demonstrates how to use throw statements in combination with try…catch blocks in Javascript.

The code:

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

try {
  let result = divide(4, 0);
  console.log(result);
} catch (error) {
  console.error(error.message);
}

Output:

Cannot divide by zero

Code explained: We call the divide function with the arguments 4 and 0. Since 0 is not a valid divisor, the function throws an Error object. We catch the thrown error using a try…catch block and log the error message to the console.

Fetching date from the internet

This example shows you how to handle errors that may occur when fetching data from the internet. We’ll use the following REST API en

https://api.slingacademy.com/v1/sample-data/photos

We will define an async function called fetchPhotos that fetches photo data from the URL above. If the response status is not ok, we throw an Error object with an error message. If the response status is ok, we parse the response as JSON and return it.

The code:

async function fetchPhotos(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('Failed to fetch photos');
  }
  const data = await response.json();
  return data;
}

try {
  const photos = await fetchPhotos('https://api.slingacademy.com/v1/sample-data/photos');
  console.log(photos);
} catch (error) {
  console.error(`Unable to fetch photos: ${error}`);
}

We also use a try…catch block to call the fetchPhotos function with the given URL. If the function throws an error, we catch it and log a message to the console.