Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between throw Error and console.error

Tags:

javascript

People also ask

Does console error throw an error?

Console. error() simply logs your error to the console with special formatting. When you actually throw an error you are essentially terminating execution unless you catch the error using a try catch block or some other form of error handling.

What is a console error?

The console. error() method in HTML is used to display an error message on the console. The console. error() method is used for testing purpose. The error message is sent as a parameter to the console.

What is a throw error?

The throw statement throws (generates) an error. The technical term for this is: The throw statement throws an exception. The exception can be a JavaScript String, a Number, a Boolean or an Object: throw "Too big"; // throw a text.


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.


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")


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