Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an error without throw

So recently I was asked a question :

Is there a way to throw an error without using throw in javaScript ?

As far as I knew about errors, there was only one way to throw an error in JavaScript and that was using throw statement in JavaScript like so :

var myFunc = () => {
  // some code here 
  throw 'Some error' // in a conditional 
  // some more code
}

try {
  myFunc()
}catch(e) {
  console.log(e)
}

And not knowing any other way I said No, there is no other way. But now I'm wondering whether I was right ?

So the question is whether or not you can throw a custom error in JavaScript without using throw


Restrictions :

  • Kindly no using eval , Function.
  • Don't use throw in your code

Additional :

If you can throw an error without using the word Error

like image 500
Muhammad Salman Avatar asked May 28 '18 18:05

Muhammad Salman


3 Answers

Generators do have a throw method that is usually used to throw an exception into the generator function code (at the place of a yield expression, similar to next), but if not caught it bubbles out of the call:

(function*(){})().throw(new Error("example"))

Of course, this is a hack and not good style, I have no idea what answer they expected. Especially the "no division by zero" requirement is sketchy, since division by zero does not throw exceptions in JS anyway.

like image 85
Bergi Avatar answered Sep 22 '22 18:09

Bergi


If all you want to do is throw an error then just do an invalid operation. I've listed a few below. Run them on your browser console to see the errors (tested on chrome and firefox).

var myFunc = () => {
  encodeURI('\uD800');    // URIError
  a = l;                  // ReferenceError
  null.f()                // TypeError
}


try {
  myFunc()
}catch(e) {
  console.log(e);
}
like image 27
TheChetan Avatar answered Sep 19 '22 18:09

TheChetan


function throwErrorWithoutThrow(msg) {
  // get sample error 
  try {
    NaN();
  } catch (typeError) {
    // aquire reference to Error
    let E = typeError.__proto__.__proto__.constructor;

    // prepare custom Error
    let error = E(msg);

    // throw custom Error
    return Promise.reject(error);
  }
}

throwErrorWithoutThrow("hi")
  /* catch the error, you have to use .catch as this is a promise
  that's the only drawback, you can't use try-catch to catch these errors */
  .catch((e) => {
    console.log("Caught You!");
    console.error(e);
  });
like image 21
Fabian N. Avatar answered Sep 20 '22 18:09

Fabian N.