简体   繁体   English

如何在不抛出的情况下抛出错误

[英]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 ? 有没有办法抛出错误而不使用java中的throw

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 : 据我所知,错误只有一种方法可以在JavaScript中抛出错误,并且在JavaScript中使用了throw语句,如下所示:

 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 . 不知道我说的任何其他方式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 所以问题是你是否可以在不使用throw情况下在JavaScript中抛出自定义错误


Restrictions : 限制:

  • Kindly no using eval , Function . 请不要使用evalFunction
  • Don't use throw in your code 不要在代码中使用throw

Additional : 附加:

If you can throw an error without using the word Error 如果您可以在不使用单词Error情况下抛出Error

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: 生成器确实有一个throw方法,通常用于将异常抛出到生成器函数代码中(在yield表达式的位置,类似于next ),但是如果没有捕获它,它会从调用中冒出来:

(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. 特别是“不分零”的要求是粗略的,因为除以零不会在JS中抛出异常。

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). 在浏览器控制台上运行它们以查看错误(在chrome和firefox上测试)。

 var myFunc = () => { encodeURI('\?'); // URIError a = l; // ReferenceError null.f() // TypeError } try { myFunc() }catch(e) { console.log(e); } 

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

I think, if you want to use try...catch blocks, you will need to throw something to get to the catch part. 我想,如果你想使用try...catch块,你需要抛出一些东西才能找到catch部分。 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: 如果在某些时候,你想在不必自己编写throw语句的情况下运行或死掉 ,你总是可以做一个断言:

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) {} // catched

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM