throw

The throw statement throws an exception. The execution of the code will stop, and the code will move on to the next catch block. If no catch block exists among caller functions, the program will stop running.

File Location

We will be working in the following file:

    javascript-library
        └── 1-Fundamentals
            └── 1-Grammar-and-Types
            └── 2-ControlFlow-and-ErrorHandling
                03-throw.js <----You will be working in this file.

Sample Code

So, we're looking ahead here with functions, but that's ok. We just want you to get the idea here. Let's look at a function:

function addNumbers(a, b) {
    if (isNaN(a) || isNaN(b)) {
      throw "One of the parameters is not a number";
    } else {
        return a + b;
    }
}

So in this function we are going to check if the numbers entered are numbers or not. We do this with isNaN, which means is Not a Number. If one of the numbers is not a number we'll throw an exception.

Just below the function, we'll add the try-catch block:

function addNumbers(a, b) {
    if (isNaN(a) || isNaN(b)) {
      throw "One of the parameters is not a number";
    } else {
        return a + b;
    }
}

// try-catch
try {
  addNumbers(10, 'kenn');
}
catch(error) {
  console.log(error);
}

Now, when we run this, it's going to throw an error because the second parameter kenn is not a number. So the if condition is true in the function, which means we throw the exception.

Key Takeaways

Here we look ahead at functions. Some of this will make more sense when we get there. For now, you should know about the throw keyword. It allows you to take control over exceptions. We call this exception handling.

Last updated