文章
问答
冒泡
try catch 如何捕获到 JS 异常

平常撸代码的时候,try catch 用的太多了,特别是一些 ”安全感" 低的人,基本是到处 try catch,生怕 JS 报错,然后页面整个挂掉了。

之前


代码报错的时候,线程执行未进入 try catch,那么无法捕捉异常。
比如语法异常(syntaxError),因为语法异常是在语法检查阶段就报错了,线程执行尚未进入 try catch 代码块,自然就无法捕获到异常。

try{
    a.
}catch(e){
    console.log("error",e);
}
// outputUncaught SyntaxError: Unexpected token '}'


之中


代码报错的时候,线程执行处于 try catch 之中,则能捕捉到异常。

  • 方法和执行都在 try 里面,能捕捉到异常。
try{
    function d(){
        a.b;
    }
    d();
}catch(e){
    console.log("error",e);
}
// outputUncaught ReferenceError: a is not defined
  • 方法定义在外部,执行方法在 try 里面,能捕捉到异常
function d(){
    a.b;
}
try{
    d();
}catch(e){
    console.log("error",e);
}
// outputerror ReferenceError: a is not defined



上述报错的时机,都是代码执行进入了 try catch ,执行 d() 方法的时候,线程执行处在 try 里面,所以能捕捉到。

之后


代码报错的时候,线程已经执行完 try catch,这种不能捕捉到异常。

例子:

try{
    setTimeout(()=>{
        console.log(a.b);
    }, 100)
}catch(e){
    console.log('error',e);
}
console.log(111);
//output
111
Uncaught ReferenceError: a is not defined



setTimeout 里面报错,实际上是 100ms 之后执行的代码报错,此时代码块 try catch 已经执行完成,111 都已经被执行了,故无法捕捉异常。

例子:

try{
    function d(){a.b;}
}catch(e){
    console.log("error",e);
}
console.log(111);
d();
// output
111
Uncaught ReferenceError: a is not defined



方法定义在 try catch 代码块里面,但是执行方法在 try catch 外,在执行 d 方法的时候报错,此时 try catch 已经执行完成,111 都已经被执行了,故而无法捕捉异常。


之后


能被 try catch 捕捉到的异常,必须是在报错的时候,线程执行已经进入 try catch 代码块,且处在 try catch 里面,这个时候才能被捕捉到。


关于作者

Roy
获得点赞
文章被阅读