Error handling is one of the things you must do when programming. Input may be abnormal or the device may fail. In short, things can go wrong, and when they do, it’s the programmer’s responsibility to make sure the code works.
In JavaScript, for error handling, we usually use try catch to catch exceptions. We use catch to catch exceptions where we think there might be exceptions, rather than everywhere. It is much easier to specialize in catching and responding to the exceptions you expect to encounter, rather than implementing a comprehensive catch.
Let’s start with a try-catch-finally statement
In a sense, a try block is like a transaction. The catch block maintains the program in a persistent state, no matter what happens in the try block. So when writing code that might throw an exception, it’s a good idea to write a try-catch-finally statement first. This helps you define what users of your code should expect, regardless of what goes wrong in the code executing in the try block.
In my understanding, the purpose of try-catch first is also to remind us that we’re going to handle exceptions here so we can write the template so we don’t forget.
Describes the environment in which the exception occurs
Every time an exception is thrown, sufficient context should be provided to determine the source and location of the error. Of course, it would be nice to have a logging system that can record all exceptions.
Do not return and pass null values
To discuss error handling, it is important to mention the practices that are prone to error. The first is to return NULL. If a null value is returned, a null judgment will appear on almost every line. The code will look bloated and ugly.
In most programming languages, there is no good way to deal with null accidentally passed in by the caller. Instead of returning null in a method, throw an exception or return a special case object.