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:
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:
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:
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