最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to throw an error without throw - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked May 28, 2018 at 18:41 Muhammad SalmanMuhammad Salman 4451 gold badge6 silver badges18 bronze badges 6
  • Does constructing the string "throw" and using e.g. eval count? – ASDFGerte Commented May 28, 2018 at 18:43
  • @ASDFGerte : No eval kindly – Muhammad Salman Commented May 28, 2018 at 18:43
  • Did the question include the ability to, for example, divide by zero? – slash_rick_dot Commented May 28, 2018 at 18:43
  • @slash_rick_dot : No division by zero (the question forbade me from division completely) – Muhammad Salman Commented May 28, 2018 at 18:44
  • 1 Codewars, amirite? :D – Manuel Otto Commented Jun 7, 2018 at 8:14
 |  Show 1 more comment

5 Answers 5

Reset to default 5

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.

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

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

I think, if you want to use try...catch blocks, you will need to throw something to get to the catchpart. You can use pretty much everything that fails with an error to do that (like mentioned in the other posts).

If at some point, you want to run-or-die without having to write the throw statement yourself, you can always do an assertion:

const myFunction = () => {
  try {
    assert.fail();
    console.log(`Did not work :)`);
  } catch (e) {
    console.log(`OK`);
  }
};

Of course I would rather try to assert something positive (more Zen), that I need in order to continue.

const myTypeErr = () => `This is a Custom Err Message... \nand it`()

try {
  myTypeErr()
} catch(e) {} // caught

myTypeErr() // Uncaught TypeError: "This is a Custom Err Message... 
              // and it" is not a function
发布评论

评论列表(0)

  1. 暂无评论