Hello! In this lesson I would like to talk about errors in JavaScript and how to actually handle them. After all, it often happens that errors occur from time to time, and it’s not even a matter of having programming experience or even a complete lack of it. After all, seasoned programmers also make mistakes; no one is immune from this.
Errors are mainly of 2 types - syntactic and logical. Syntactic errors include errors in the names of variables, functions, and errors in code syntax. In principle, such errors are easy to catch through the browser console.
But logical errors are not so simple with them because they lead to incorrect execution of the program code. Therefore, to eliminate them, you will need to debug the program in order to understand what actually happens at each step of the script. Here we will mainly consider the localization of syntax errors using the try...catch construct.
Try…catch error catching structure
The try..catch construct consists of 2 blocks: try, and then catch. Here is an example of a general entry
Try ( // code... ) catch (err) ( // error handling )
This design works like this:
Therefore, if there is an error in try, the script does not stop, and even moreover, we have the opportunity to handle the error inside the catch block.
Let's look at this with examples.
- Example without errors: at startup, alert (1) and (2) will be triggered: try ( alert("Try Block"); // (1)