Javascript 我可以在JS中打破一个try-catch而不抛出异常吗?
如果条件适用,我想在Javascript 我可以在JS中打破一个try-catch而不抛出异常吗?,javascript,operators,try-catch,Javascript,Operators,Try Catch,如果条件适用,我想在try块中无声地打断try-catch。(不抛出不必要的异常) 但是,return不是选项,因为函数应该在之后继续执行 更新 我仍然希望有机会使用finally块。您可以使用break label语法标记块并从中断开 根据您的编辑,最终仍将执行 foo = function(){ var bar = Math.random() > .5; omgalabel: try { if( bar ) break omgalabel;
try
块中无声地打断try
-catch
。(不抛出不必要的异常)
但是,return
不是选项,因为函数应该在之后继续执行
更新
我仍然希望有机会使用
finally
块。您可以使用break label语法标记块并从中断开
根据您的编辑,最终仍将执行
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 );
}
}
为什么不在输入try…catch
之前检查布尔值
var error;
var bar = Math.random() > .5;
try{
if(bar){throw new Error('#!@$');} // Break this try, even though there is no exception here.
// This code should not execute if !!bar
alert( bar );
}
catch(e){
if(e.stack.indexOf('#!@$')==-1){error=e;}
}
finally{
if(error){
//an actual error happened
}
else{
// Code that executes if !!bar
alert( true );
}
}
您可以在try-catch中抛出一个错误,并检测错误堆栈的字符串,以查看它是预期的抛出还是未预期的实际错误如果(!bar)呢?(如果在try块中的其余代码周围)如果出现
!bar
,代码应继续执行,并带有行警报(bar)代码>@StevenPalinkas:blablabla意思是这样的smthif(!bar){alert(bar);}
@Andrey:这就是我的意思。谢谢。我必须知道,为什么有人需要这个?如果感觉像是有一个例子。更简单和更干净的解决办法是不进入试一试。如果酒吧是真的。标签被视为等同于GOTO,很少使用。哇,你可以使用标签打破非循环?@RobG向皈依者布道,但问题显然被简化了,我们该评判谁。你希望有人重写2000行代码,只是因为你说try/catch不好。有时作为程序员,我们需要处理其他人的代码,有时重写不是首要任务。因此,虽然我同意你的观点,并且这个评论对这个问题是正确的,但没有必要在回答中反复提及,是吗?@Kos我大约10分钟前就知道了——我自己永远也看不到有必要这样做,但我也避免尝试/抓住,因为我感谢你教我这一点。“我不在乎人们怎么看我们,GOTO婚姻现在在Javascript中是合法的,”hurray:Das OP在他的问题中说-这是一个简化的问题example@JaromandaX,即使简化了这个例子,问题仍然存在。如果这是不可能的,我想是时候重构了:)
foo = function(){
var bar = Math.random() > .5;
if( ! bar ) {
try{
// This code should not execute if !!bar
alert( bar );
}
catch( e ){
console.error(e);
}
}
// Code that executes no matter what
alert( true );
}
foo();
var error;
var bar = Math.random() > .5;
try{
if(bar){throw new Error('#!@$');} // Break this try, even though there is no exception here.
// This code should not execute if !!bar
alert( bar );
}
catch(e){
if(e.stack.indexOf('#!@$')==-1){error=e;}
}
finally{
if(error){
//an actual error happened
}
else{
// Code that executes if !!bar
alert( true );
}
}