JavaScript throw statement

The javaScript throw statement can be used to internationally throw a user-defined exception. It can be used as a way to stop execution of a javaScript program in the event that some kind of essential condition is not in order.

1 - javaScript throw basics

To use a throw statement just type the throw keyword followed by a value that reflects what the error is about. The value can be a string, number boolean or an object that should be given certain standard key value pairs more on that later.

1
2
3
4
5
6
7
8
9
var addNumbers = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw 'must give numbers';
}
return a + b;
};
console.log( addNumbers(15,5) ); // 20
addNumbers('foo', []); // Error must give numbers

2 - javaScript throw defined with an object

So a string can be used to describe the user defined Error, but it might be best to use an Object or The Error constructor to create an object with message and name properties that help to better identify what is wrong when the Error is thrown.

1
2
3
4
5
throw {
message: 'this error is defined with an object',
name: 'ObjectDefinedError'
}
// ObjectDefinedError: this error is defined with an object

3 - javaScript throw and try catch blocks

When an Error is thrown any catch statement present will of course be executed which can be used to handal the Error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var process = function (str) {
if (str === 'bar') {
console.log('foobar');
}
throw {
message: 'must give bar',
name: 'NoBarError'
};
};
try {
process('foo');
} catch (e) {
console.log(e.message); // 'must give bar'
}