Home > Article > Web Front-end > How to use JavaScript Try...Catch statement_Basic knowledge
The purpose of try...catch is to test errors in the code.
Example
try...catch statement
How to write try...catch statement.
try...catch statement with confirmation box
Another example of writing a try...catch statement. JavaScript - Catching Errors
When we surf the Internet, we will always see a Javascript warning box with runtime errors, and we will be asked "Do you want to debug?". Error messages like this may be useful to developers, but not necessarily to users. When errors occur, they often choose to leave the site.
This section explains to you how to capture and handle Javascript error messages so that you can provide more convenience to your audience.
There are two ways to catch errors in a web page:
Use try...catch statement. (Available in IE5, Mozilla 1.0, and Netscape 6)
Use the onerror event. This is the old-fashioned way of catching errors. (Available in versions after Netscape 3)
Try...Catch statement
try...catch can test errors in the code. The try section contains the code that needs to be run, while the catch section contains the code that is run when an error occurs.
Syntax:
try
{
//Run code here
}
catch(err)
{
//Handle errors here
} Note: try...catch uses lowercase letters. Capital letters will go wrong.
Example 1
The following example was originally used to display the "Welcome guest!" message when the user clicks the button. However, alert() in the message() function is mistakenly written as addlert(). At this time the error occurred: