How to throw an exception in JavaScript?

JavaScript provides a throw operator to throw exceptions.

For simple cases, you can just throw a message:

if (!accountFound) {
	throw "Sorry, there was a problem fetching the account details";
}

We can catch this error with a try catch:

try {
	accountFound = false;
	if (!accountFound) {
		throw "Sorry, there was a problem fetching the account details";
	}
}
catch (e) {
	console.log(e);
}

However, you can throw objects as well. A good convention to follow would be to throw an object containing a name and a message.

if (!accountFound) {
	throw {
		name: 'AccountFetchFailed',
		message: 'Sorry, there was a problem fetching the account details'
	}
}

Then we can check for different kinds of errors that might be thrown and react accordingly.

try {
	accountFound = false;
	if (!accountFound) {
		throw {
			name: 'AccountFetchFailed',
			message: 'Sorry, there was a problem fetching the account details'
		}
	}
}
catch (e) {
	// Check which kind of exception was thrown.
	if (e.name == 'AccountFetchFailed') {
		console.log(e.message);
	}
}

If you need to reuse exceptions you may like to create an object for your exception.

function AccountFetchFailed(message) {
	this.name="AccountFetchFailed";
	this.message = message;
}

Which might be used like this:

try {
	accountFound = false;
	if (!accountFound) {
		throw new AccountFetchFailed('Sorry, there was a problem fetching the account details');
	}
}
catch (e) {
	if (e.name == 'AccountFetchFailed') {
		console.log(e.message);
	}
}
You can leave a response, or trackback from your own site.

Leave a Reply