Reputation: 1827
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
}
}
Upvotes: 0
Views: 113
Reputation: 1975
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.
Upvotes: 0
Reputation: 8424
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;
}
}
Upvotes: 0
Reputation: 7514
You must re-throw the exception:
...
catch(e) {
alert('error occurred');
throw(e);
}
Upvotes: 1
Reputation: 349252
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.
Upvotes: 2