JavaScript Errors - throw, try and catch
tryThe statement tests a code block for errors.
catchThe statement handles errors.
throwThe statement creates custom errors.
finallyThe statement executes after the try and catch statements, regardless of whether an exception was triggered.
JavaScript Errors
When the JavaScript engine executes JavaScript code, various errors can occur.
They may be syntax errors, usually coding errors or typos made by programmers.
They may be spelling errors or missing features of the language (possibly due to browser differences).
They may be errors caused by incorrect output from the server or the user.
Of course, they may also be due to many other unpredictable factors.
JavaScript Throwing Errors (throw)
When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.
The technical term for this situation is: JavaScript willthrowan error.
JavaScript try and catch
tryThe statement allows us to define a block of code that is tested for errors during execution.
catchThe statement allows us to define a block of code to be executed when an error occurs in the try block.
JavaScript statementstryandcatchcome in pairs.
Syntax
Example
In the following example, we deliberately wrote a typo in the code of the try block.
The catch block will catch the error in the try block and execute code to handle it.
Example
Try it Yourself »
The finally Statement
The finally statement executes the code block regardless of whether an exception occurred in the preceding try and catch.
Example
Try it Yourself »
The Throw Statement
The throw statement allows us to create custom errors.
The correct technical term is: create orthrow an exception(exception)。
If you use throw together with try and catch, you can control the program flow and generate custom error messages.
Syntax
The exception can be a JavaScript string, number, boolean, or object.
Example
This example checks the value of an input variable. If the value is wrong, an exception (error) is thrown. catch will catch this error and display a custom error message:
Example
Try it Yourself »
Note that if the getElementById function fails, the example above will also throw an error.
Other extensions