Which operator is used to throw javascript exceptions. JavaScript: Exceptions. Functions for getting error information

💖 Do you like it? Share the link with your friends

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:

  • The code inside the try block, the so-called trap, is executed.
  • If no errors are encountered, the catch(err) block is ignored.
  • But if an error occurs in it, then the execution of the try will be interrupted on the error, and control is transferred to the beginning of the catch(err) block. In this case, the err variable (you can choose any other name) will contain an error object with detailed information about the error that occurred.
  • 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)

    tell friends