试试......抓住

try … catch 块用于处理异常,记住异常意味着抛出错误而不是错误。

try {
    var a = 1;
    b++; //this will cause an error because be is undefined
    console.log(b); //this line will not be executed
} catch (error) {
    console.log(error); //here we handle the error caused in the try block
}

try 块中 b++导致错误,并且错误传递给 catch 块,可以在那里处理,甚至可以在 catch 块中抛出相同的错误或者稍微修改然后抛出。我们来看下一个例子。

try {
    var a = 1;
    b++;
    console.log(b);
} catch (error) {
    error.message = "b variable is undefined, so the undefined can't be incremented"
    throw error;
}

在上面的例子中,我们修改了 error 对象的 message 属性,然后抛出修改后的 error

你可以通过 try 块中的任何错误并在 catch 块中处理它:

try {
    var a = 1;
    throw new Error("Some error message");
    console.log(a); //this line will not be executed;
} catch (error) {
    console.log(error); //will be the above thrown error 
}