What is the difference between throw Error and console.error

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?


Solution 1:

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.

Solution 2:

Some of the Differences are:

throw Error("msg"):

  1. Stops js execution.
  2. Mostly used for code handling purpose.
  3. Can alter main flow of execution.
  4. This syntax is mostly same for all browser as this is specified and validated by W3C.

console.error("msg"):

  1. It just shows output in Red color at Browser console
  2. It is mostly used to print values for debugging purpose.
  3. Cannot harm main flow of execution.
  4. This Syntax sometimes vary according to vendor browser and not standardized by W3C.

    i.e. For IE accepted syntax is window.console.debug("msg")

Solution 3:

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