Developer Defined Errors

We can also throw our own errors. This is done with the “throw” keyword using the “new” keyword and the Error method. Here is the syntax…

try {
    let animal = newAnimal;
    throw new Error(‘This is a custom error being thrown’);
} catch(error){
    console.log(‘error: ‘, error);

Why would we do this? There might be times when your code logic won’t throw a JavaScript error, but something happens that you want to catch so no issues show up later for the end user. For example, you can test whether a variable has a value and if not, throw an error.

Happy Coding!

Clay Hess