JavaScript Try ... Catch statement
Description: The Try...carch statement in JavaScript acts in the same way as the Try...catch statement in C #,
is to catch and handle exceptions.
Grammar:
try
{ //Run code here} catch(err)
{ //handling errors here}
Example:
varTxt= ""functionmessage () {Try{Adddlert ("Welcome guest!")}Catch(err) {txt= "There was a error on this page.\n\n"txt+ = "Click OK to continue viewing this page,\n"txt+ = "or Cancel to return to the home page.\n\n"if(!confirm (TXT)) {Document.location.href= "http: ..." }}}</script>The example above shows a confirmation box that allows the user to choose whether to click the OK button to continue browsing the page when an error occurs, or to click the Cancel button to access other pages.
JavaScript Throw DeclarationDescription: The purpose of the throw declaration is to create a exception (exception or error).
The purpose of the throw declaration is to create a exception (exception). You can use this statement in conjunction with the Try...catch Declaration to achieve control
The purpose of the program flow and produces an accurate error message.
Grammar:
Throw (Exception)
Exception can be a string, an integer, a logical value, or an object. (Throw must be lowercase)
Example:varX=prompt ("Please enter the number from 0 to 10:", "" ")Try{if(x>10)Throw"ERR1"Else if(x<0)Throw"ERR2"Else if(IsNaN (x))Throw"Err3"}Catch(er) {if(er== "ERR1") Alert (Error The value is too large! ")if(er = "Err2")) Alert (Error The value is too small! ")if(er = "ERR3")) Alert (Error This value is not a number! ")}</script></body>The function of the above example is to determine the value of the variable x. If the value of X is greater than 10 or less than 0 or is not a number, the error is thrown (throw). When the error is captured by the catch parameter, a custom error message is displayed.
JavaScript onerror EventsDescription: Using the OnError event is an old-fashioned standard method of capturing Javascript errors in a Web page.
Chrome, opera, Safari browser not supported
The OnError event is generated whenever a script error occurs on the page.
If you need to take advantage of the OnError event, you must create a function that handles the error. You can think of this function as the OnError event handler (onerror events handler). This event handler uses three parameters
Number to invoke: MSG (error message), URL (the URL of the page where the error occurred), line (the lines of code where the error occurred).
Grammar:
Onerror=handleerrfunction Handleerr (msg,url,l) {//handle The error here return TRUE or False}
Example:onerror=HandleerrvarTxt= ""functionHandleerr (msg,url,l) {txt= "There was a error on this page.\n\n"txt+ = "Error:" + msg + "\ n"txt+ = "url:" + URL + "\ n"txt+ = "line:" + L + "\ n"txt+ = "Click OK to continue.\n\n"alert (TXT)return true}functionmessage () {Adddlert ("Welcome guest!")}</script>JavaScript Error/exception handling