What is the difference between throw Error and console.error

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3886234View Question on Stackoverflow
Solution 1 - JavascriptmichalhView Answer on Stackoverflow
Solution 2 - JavascriptPramod S. NikamView Answer on Stackoverflow
Solution 3 - JavascriptMichael Aaron SafyanView Answer on Stackoverflow