From the course: Learn JavaScript: Write Modern Code with JavaScript ESNext

Unlock this course with a free trial

Join today to access over 25,000 courses taught by industry experts.

Handle and throw errors in JavaScript

Handle and throw errors in JavaScript

- The next thing we're going to look at is handling errors in JavaScript. Just like in most other programming languages, there are places in our programs where we might need to anticipate errors and provide some way of dealing with them when they occur. And this is especially true when our programs are doing things like making network requests or reading files, where something could go wrong unexpectedly. Instead of just letting the program crash in these cases, we usually want to let the user down gently, so to speak. The way we do this in JavaScript, which again is probably pretty similar to whatever language you're coming to JavaScript from, is by using something called a try/catch block. And here's what that looks like. We have a try block, which contains some code that might throw an error, and this is followed by a catch block, which will get executed if an error does occur inside the try block. The catch block has a pair of parentheses that give us access to the actual error…

Contents