Http://www.w3school.com.cn/js/js_errors.asp
The Try statement tests the code block for errors. the catch statement handles the error. The throw statement creates a custom error.
mistakes are bound to happen .
When the JavaScript engine executes JavaScript code, various errors occur:
It could be a syntax error, usually a coding error or typo caused by a programmer.
It may be a misspelling or a missing feature in the language (possibly due to browser differences).
The error may be caused by error output from the server or user.
Of course, it may also be due to many other unpredictable factors.
JavaScript throws an error
When an error occurs, the JavaScript engine usually stops and generates an error message when something goes wrong.
The technical term that describes this situation is that JavaScript throws an error.
JavaScript Testing and capturing
The Try statement allows us to define a block of code that performs error testing at execution time.
The catch statement allows us to define a block of code that executes when a try block of code has an error.
The JavaScript statement try and catch are paired occurrences.
Grammar
Try { //Run code here }catch (err) { //Handle error here }
Example
In the following example, we deliberately write a typo in the code of the try block.
The catch block catches the error in the try block and executes the code to handle it.
<! DOCTYPE html>adddlert (" Welcome guest! "); } catch (Err) { txt= "there is an error in this page.\n\n"; txt+= "Error Description:" + err.message + "\ n"; txt+= "Click OK to continue.\n\n"; alert (TXT);} } </script>
Try it yourself.
Throw Statement
The throw statement allows us to create custom errors.
The correct technical term is: Create or throw an exception (exception).
If you use throw with try and catch, you can control the flow and generate custom error messages.
Grammar
exception
An exception can be a JavaScript string, a number, a logical value, or an object.
Example
This example detects the value of the input variable. If the value is wrong, an exception (error) is thrown. Catch catches this error and displays a custom error message:
<script>function myFunction () {try { var X=document.getelementbyid ("Demo"). Value; if (x== "") throw "empty"
; throw "not a number"
; if (x>10) throw "too high"
; if (x<5) throw "too low"
; } catch (Err) { var Y=document.getelementbyid ("mess"); Y.innerhtml= "Error:" + Err + "."; }} </script>
JavaScript errors-Throw, Try, and Catch