我可以尝试一下-在JS中捕获而不抛出异常吗?

Ste*_*kas 3 javascript try-catch operators

如果有条件,我想在区块中默默地打破try- 。(不会引发不必要的异常)catchtry

foo = function(){

    var bar = Math.random() > .5;

    try{

          if( bar ) // Break this try, even though there is no exception here.

          //  This code should not execute if !!bar 

          alert( bar );

    }
    catch( e ){}

    // Code that executes if !!bar

    alert( true );

}

foo();
Run Code Online (Sandbox Code Playgroud)

但是,return这不是一个选择,因为该函数应在此后继续执行。

更新

我想仍然保持使用该finally块的机会。

Jar*_*a X 7

您可以标记一个块并使用中断标签语法从中中断

根据您的编辑,最后仍然执行

foo = function(){
    var bar = Math.random() > .5;
    omgalabel: try {
        if( bar ) break omgalabel;
        console.log( bar );
        // code 
    }
    catch( e ){
        //  This code should not execute if !!bar 
    }
    finally {
        // Code that executes no matter what
        console.log( true );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @RobG 向皈依者传道,但由于问题显然被简化了,我们该评判谁。你希望有人重写 2000 行代码,只是因为你说 try/catch 不好,嗯嗯。有时,作为程序员,我们需要处理其他人的代码,有时重写并不是第一要务。因此,虽然我同意你的观点,并且该评论对这个问题是有效的,但没有必要在答案中喋喋不休,不是吗? (4认同)
  • 更简单、更干净的解决方案是,如果 *bar* 为真,则根本不输入 *try..catch*。标签被认为相当于 GOTO,并且极少使用。 (3认同)
  • 谢谢你教我这个。我不在乎人们怎么看我们,GOTO 婚姻现在在 Javascript 中是合法的,万岁:D (2认同)
  • 它不是一个 goto,甚至不是关闭...它打破了一个标记块(标签位于break语句之上,它不允许您跳转到任意标记块 - 嵌套标记块也可以很有趣 - https:// /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break - 它更接近于内部函数中的返回......有点 (2认同)