1.跟java一样,javascript也具有try catch块,进行异常捕获的机制。
(1)典型的try catch语句
try{
}
catch{
}
finally{
}
跟java中一样,JS中最为典型的try catch语句也同样分为了三个部分,try用于捕获异常,catch用于处理异
常,而finally用于关闭资源等后续操作。
举例:try{
throw "error"
}
catch(ex)
{
console.log(ex);
}
finally{
console.log("finally")
}
控制台依次输出:error,finally
(2)try,catch块中,catch块和finally块只需要其一即可,因此如下的try catch块也是可以实现的
举例:
try {
throw "error"
}
finally{
}
只抛出异常,其他情况不一一举例
(3)try catch块中包含了try catch块
try{
try{
throw "error"
}
finally{
console.log("finally1")
}
}
catch(ex)
{
console.log(ex)
}
finally{
console.log("finally2")
}
如果是像这样的嵌套循环,那么输出的顺序为:finally1,error,finally2
(4)嵌套try catch块中,抛出异常
try{
try{
throw "error1"
}
catch(ex)
{
console.log(ex);
throw "error2"
}
finally{
console.log( "finally1")
}
}
catch(ex)
{
console.log(ex);
}
finally{
console.log("finally2")
}
最终的输出为:error1,finally1,error2,finally2