Can I break a try - catch in JS without throwing exception?
You can label a block and break from it using the break label syntax
as per your edit, finally is still executed
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 );
}
}
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 );
}
}
you can throw a error inside try catch and detect the string of the error stack to see if it was an expected throw or an actual error you didn't expect
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();
Why don't you check the boolean before you enter the try…catch
?