Reputation:
What is the difference between these two statements, and is there a good reason to use one over the other?
throw Error("msg");
console.error("msg");
In my limited experience, I've only really seen throw Error()
used. Is there any particular reason why?
Also, is there an equivalent to console.warn()
in the same fashion?
Upvotes: 78
Views: 36891
Reputation: 4549
Some of the Differences are:
throw Error("msg"):
console.error("msg"):
This Syntax sometimes vary according to vendor browser and not standardized by W3C.
i.e. For IE accepted syntax is window.console.debug("msg")
Upvotes: 34
Reputation: 2997
throw ...
raises an exception in the current code block and causes it to exit, or to flow to next catch
statement if raised in a try
block.
console.error
just prints out a red message to the browser developer tools javascript console and does not cause any changes of the execution flow.
Upvotes: 94
Reputation: 95589
Throw is for actually changing the control flow (jumping out of the current context and up to an error handler) for handling errors programmatically. The console statement is just for debugging and printing text to the error console. You may see them used in conjunction, for example:
var doSomethingDangerous = function(response) {
if (isMalformed(response)) {
throw Error('Response is malformed.');
}
process(response);
};
var sendAsyncRequest = function() {
var request = buildAsyncRequest();
request.sendThen(function (response) {
try {
doSomethingDangerous(response);
} catch (e) {
console.error(e);
doSomeAdditionalErrorHandling();
}
});
};
Upvotes: 3