JavaScript Error - How To throw, try and catch the

try  error test code block statements.

catch  statement handles the error.

throw  statement creates custom error.

finally  statement after the try and catch statements, regardless of whether an exception is triggered, the statement will be executed.

JavaScript try 和 catch

try  statement allows us to define the code block error test at the time of execution.

catch  statement allows us to define a block of code when an error occurs when the try block, performed.

JavaScript statement to  try  and  catch  in pairs.

grammar

the try { 
    ...     // exception thrown 
} the catch (E) { 
    ...     // abnormality capture and processing 
} the finally { 
    ...     // process ends 
}

finally statement

finally statement whether produced prior to try and catch the exceptions are to execute the code block.

Example:

function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "") throw "值是空的";
    if(isNaN(x)) throw "值不是一个数字";
    x = Number(x);
    if(x > 10) throw "太大";
    if(x < 5) throw "太小";
  }
  catch(err) {
    message.innerHTML = "错误: " + err + ".";
  }
  finally {
    document.getElementById("demo").value = "";
  }
}

Throw Statement

throw statement allows us to create custom error.

The correct technical term is: create or throws an exception (exception).

If used with a try to throw and catch, you can control program flow and generate a custom error messages.

Example: This example of the detection value of the input variables. If the value is wrong, it will throw an exception (error). catch will catch the error and display an error message for a custom:

function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "")  throw "值为空";
        if(isNaN(x)) throw "不是数字";
        x = Number(x);
        if(x < 5)    throw "太小";
        if(x > 10)   throw "太大";
    }
    catch(err) {
        message.innerHTML = "错误: " + err;
    }
}

Note: If the getElementById function error, the above example will throw an error.

Guess you like

Origin www.cnblogs.com/art-poet/p/12098339.html
Recommended