JavaScript error - Throw, Try and Catch
Error statement tests try code block.
catch statement handles the error.
throw statement creates custom error.
JavaScript error
When the JavaScript engine executes JavaScript code, various errors occur.
May be a syntax error is usually caused by programmers coding errors or typos.
Language may be misspelled or missing features (may be due to differences in browser).
It may be erroneous due to the error output from a server or a user of the result.
Of course, it may be due to many other unpredictable factors.
JavaScript throw (throw) Error
When an error occurs, when things go wrong, JavaScript engine will typically stop and generate an error message.
The technical term to describe this situation is: JavaScript will throw an error.
JavaScript try and catch
try to define statement allows us to test for errors in the implementation of the code block.
catch statement allows us to define a block of code when an error occurs when you try code block, executed.
JavaScript try and catch statements appear in pairs.
grammar
try { //在这里运行代码 } catch(err) { //在这里处理错误 }
Examples
In the following example, we deliberately wrote a typo in the code try block.
to try catch block will catch block error, and execute the code to handle it.
Examples
function message ()
{
try {
adddlert ( "Welcome guest!") ;
} Catch (err) {
txt = "This page has an error \ n \ n.";
txt + = "Error description:" + err.message + "\ n \ n";
txt + = "Click OK to continue \ n \ n.";
alert (txt);
}
}
try it"
Throw Statement
throw statement allows us to create custom error.
The correct technical term is: create or throws an exception (exception).
If the throw and try and catch used together, you can control program flow and generate a custom error message.
grammar
JavaScript exception can be a string, number, logical value or object.
Examples
In this case the value of the detection of the input variables. If the value is wrong, it throws an exception (error). catch will catch this error, and displays an error message for some custom:
function myFunction() { try { var x=document.getElementById("demo").value; if(x=="") throw "值为空"; if(isNaN(x)) throw "不是数字"; if(x > 10) throw "太大"; if(x < 5) throw "太小"; } catch(err) { var y=document.getElementById("mess"); y.innerHTML="错误:" + err + "。"; } }
Please note that if getElementById function error, the above example will throw an error.