In this lesson, let's discuss the fundamental building blocks of error handling, that is, error objects and the try-catch syntax. js. js. This same pattern will be followed for the rest of the course.
Now in JavaScript, when something goes wrong, the language throws an error object. We can create our own error objects by newing up an instance of the error class and providing a descriptive message. Let's say that maybe a requested user was not found. This error object can now be thrown to prevent further execution of the program.
Let's add a console log after the thrown error and test things out in the browser. just to confirm this. Inside of my running application, if I navigate to lesson two, try catch begin, then you'll see that sure enough, we only have the error logged to the console. We never get to the console log that says the program continues.
This isn't ideal. We probably don't want this one error to cause the whole app to stop. So what do we do? Well, we can use a try-catch block to wrap code that carries the risk of throwing errors.
Catch the error if it's thrown, and then provide a more appropriate response than just stopping the app. In this simple demo, we'll just console log the error message. But in real life, the handling would depend on a variety of different factors. But we'll dive more into that topic later.
All right, let's break this down one more time. The try block contains code that might throw an error. If an error occurs, execution immediately then jumps to the catch block. The catch block receives the thrown error as a parameter.
Finally, code after the try catch block continues executing as normal. We can confirm this by checking things out on the browser, and sure enough, our message, the program continues, is logged there to the console. Sometimes you need code to run whether an error occurred or not. Well, that's where a finally block comes in.
We can add it after the catch just like this. This block is perfect for cleanup tasks like closing open connections or resetting state. Try it out in the browser and yep, this works exactly as expected. We have the user not found error message logged first.
the console log within the finally blog, logged second, and then the program continues message, logged last. While this wasn't a very practical example, you should now have a very good grasp on the syntax of using try-catch.