Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何停止javascript中嵌套的try/catch错误的传播?_Javascript_Try Catch - Fatal编程技术网

如何停止javascript中嵌套的try/catch错误的传播?

如何停止javascript中嵌套的try/catch错误的传播?,javascript,try-catch,Javascript,Try Catch,function1()输出: a d b 我想要的是,如果function2出错,则返回到function1,并将输出保留在: a d 这可能吗?我想我可以在finally块中引用一个返回的布尔值(出错与否),但我想知道是否有更好的解决方案 function1(){ try { console.log("a"); function2(); console.log("b"); } catch

function1()
输出:

a
d
b
我想要的是,如果
function2
出错,则返回到function1,并将输出保留在:

a
d
这可能吗?我想我可以在finally块中引用一个返回的布尔值(出错与否),但我想知道是否有更好的解决方案

function1(){
    try {
             console.log("a");
             function2();
             console.log("b");
         } catch (e){       
             console.log("c");
         }
}
function2(){
    try {
             if(...) throw new Error();
         } catch (e){
             console.log("d");
         }
}

我认为您确实希望代码返回,并且您应该考虑一个结构化的解决方案,以获得所需的输出

要确保function1停止执行,请让function2抛出一个错误。您可以不捕获函数2中的错误并让它们冒泡,也可以从函数2中的catch块抛出错误:

function2(){
    try {
             if(...) throw new Error();
         } catch (e){
             console.log("d");
             throw new Error();   //do this!
         }
}
此外,我意识到您可能需要更多的控制,因此您可以从函数2到函数1抛出一些内容,以使其更清晰,如下所示:

function one(){
    try {
             console.log("a");
             two();
             console.log("b");
         } catch(e){       
             console.log(e == 7);  //this is true!
         }
}

function two(){
    try {
             if(true){ throw new Error();}

         } catch(e){
             console.log("d");
             throw 7;
         }
}

one();