0

So in my app when a particular condition occurs, I want to display an alert and then stop program execution. I read somewhere that this can be done with a throw() but I'm unable to make that work.

Here's what I've tried:

function check_for_error(data) {
    try {
        if ( <error condition> ) { 
            throw "error"; 
        }
    } catch(e) {
            alert('error occured'); 
                // I want program execution to halt here but it does not, 
                // it continues within the calling code
    }
}
1
  • You can try throwing error from the catch block and then handling it in the callee method. And essentially exit. Commented Dec 16, 2011 at 19:10

4 Answers 4

2

You should throw another error in the catch block. Or not catch the initial error at all.

Currently, the following happens:

<error condition me>
throw "error"
catch error and  Show alert

To "halt" the execution, you have to add throw e after the alert (in the catch block):

catch(e) {
    alert('error occurred');
    throw e;
}

If your function is called from within another try-catch block, you also have to apply a similar mechanism to that block.

Sign up to request clarification or add additional context in comments.

Comments

1

You must re-throw the exception:

...
catch(e) {
    alert('error occurred');
    throw(e);
}

1 Comment

Ok got it to work by doing the above, then in the calling function putting the call in a try / catch, with the catch empty. Thanks.
0

and also you can

function check_for_error(data) {
    try {
       //WHEN ERROR OCCURES
    } catch(e) {
            alert('error occured'); 
                // I want program execution to halt here but it does not, 
                // it continues within the calling code
            throw(e);
            return;
    }
}

Comments

0

Throw only will stop execution of synchronous rutines, For example if you made an asynchronous http request it will execute the callback function regardless of a previous error.

Throw doc from w3c:

Syntax

throw exception

The exception can be a string, integer, Boolean or an object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.