I'd like to silently break a try
- catch
in the try
block if a condition applies. ( Without throwing an unneccessary exception )
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();
However, return
is not an option, since the function is supposed to continue executing afterwards.
UPDATE
I'd like to still keep up the opportunity to use the finally
block.
You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.
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();
When your code throws a checked exception, you must either use a try block to catch it, or use the throws keyword on your method to advertise the fact that it throws an exception to any method that may call it, so that it in turn must either use a try block to catch it or use the throws keyword to pass the buck.
The “try… First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With