Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I break a try - catch in JS without throwing exception?

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.

like image 599
István Pálinkás Avatar asked Aug 13 '15 12:08

István Pálinkás


People also ask

Can you break out of try catch?

You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.

How do you break from TRY block in JS?

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();

Does a try catch need a throw?

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.

Does try catch stop execution JavaScript?

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) .


1 Answers

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 );
    }
}
like image 166
Jaromanda X Avatar answered Oct 18 '22 17:10

Jaromanda X