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块的机会。
您可以标记一个块并使用中断标签语法从中中断
根据您的编辑,最后仍然执行
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)