"throw new Warning" in JavaScript?

At the moment I'm extending my JavaScript project with error handling. The throw statement is playing an important role here:

throw new Error("text"); // Error: text

However, can I also throw a warning? I tried the following to no avail:

throw new Warning("text"); // Warning is not defined

The errors make Chrome's Developer Tools show a red cross, but how can I make it display a warning icon (yellow exclamation mark)?


Like this:

console.warn('Hi!');

Note that unlike exceptions, this will not interrupt your code; the calling function will continue normally.

Also note that this will throw an error in any browser except for WebKits or Firefox with Firebug, because console won't exist.

To fix that, you can include Firebug Lite, or make a fake NOP-ing console object.


There's no such thing as a "warning" exception. When you throw an object (and you can throw pretty much anything), it's an exception that's either caught or not.

You could possibly achieve a warning effect by making sure your code intercepts exceptions coming up from inside your code, looking for "warning" objects somehow (by type or by duck-typing).

edit This has attracted some downvotes over the years, so I'll expand on the answer. The OP asked explicitly "can I also throw a warning?" The answer to that could be "yes" if you had a "Warning" constructor:

function Warning(msg) {
  this.msg = msg;
}

Then you could certainly do

if (somethingIsWrong())
  throw new Warning("Something is wrong!");

Of course, that'll work, but it's not a whole lot different from

if (somethingIsWrong())
  throw "Something is wrong!";

When you're throwing things, they can be anything, but the useful things to throw are Error instances, because they come with a stack trace. In any case, there's either going to be a catch statement or there isn't, but the browser itself won't care that your thrown object is a Warning instance.

As other answers have pointed out, if the real goal is just affecting console output, then console.warn() is correct, but of course that's not really comparable to throwing something; it's just a log message. Execution continues, and if subsequent code can't deal with the situation that triggered the warning, it'll still fail.