我可以在不抛出异常的情况下中断 try - catch 吗?
Can I break a try - catch in JS without throwing exception?
如果条件适用,我想默默地打破 try
块中的 try
- catch
。 (不抛出不必要的异常)
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();
但是,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 );
}
}
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();
为什么不在输入 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 中抛出一个错误,并检测错误堆栈的字符串,看看它是一个预期的抛出还是一个你没有预料到的实际错误
如果条件适用,我想默默地打破 try
块中的 try
- catch
。 (不抛出不必要的异常)
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();
但是,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 );
}
}
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();
为什么不在输入 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 中抛出一个错误,并检测错误堆栈的字符串,看看它是一个预期的抛出还是一个你没有预料到的实际错误