JS usage in try catch

try ... catch syntax

try {
    //在此运行代码
}
catch(err){
    //在此处理错误
}

运行流程:
try{...}包含块中的代码有错误,则运行catch(err){...}内的代码,
否则不运行catch(err){...}内的代码。

try...catch

var array = null;
try {
  document.write(array[0]);
} catch(err) {
  document.writeln("Error name: " + err.name + "");
  document.writeln("Error message: " + err.message);
}

try...catch...finally

There is provided a method for processing may occur to some or all of the errors in a given code block, while still running the code. If the programmer does not handle the error occurred, JS only its common error message to the user, the same as if no error handling.

var array = null;
try {
  document.write(array[0]);
} catch(err) {
  document.writeln("Error name: " + err.name + "");
  document.writeln("Error message: " + err.message);
}
finally{
  alert("object is null");
}

程序执行过程

1. array[0]的时候由于没有创建array数组,array是个空对象,程序中调用array[0]就会产生object is null的异常 
2. catch(err)语句捕获到这个异常通过err.name打印了错误类型,err.message打印了错误的详细信息. 
3. finally类似于java的finally,无论有无异常都会执行.

Guess you like

Origin www.cnblogs.com/xiaobaiv/p/12653763.html