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.
console.warn('text');return
? So basically is one able to create a function that acts as areturn
statement at the place the function is called? – Holds