So recently I was asked a question :
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
eval
, Function
.throw
in your codeIf you can throw an error without using the word Error
答案 0 :(得分:3)
生成器确实有一个throw
方法,通常用于将异常抛出到生成器函数代码中(在yield
表达式的位置,类似于next
),但是如果没有抓住它的气泡:
(function*(){})().throw(new Error("example"))
当然,这是一个黑客而不是好的风格,我不知道他们的期望是什么。特别是"没有除零"要求是粗略的,因为除以零不会在JS中抛出异常。
答案 1 :(得分:3)
如果您只想抛出错误,那么只需执行无效操作即可。我在下面列出了几个。在浏览器控制台上运行它们以查看错误(在chrome和firefox上测试)。
var myFunc = () => {
encodeURI('\uD800'); // URIError
a = l; // ReferenceError
null.f() // TypeError
}
try {
myFunc()
}catch(e) {
console.log(e);
}
答案 2 :(得分:3)
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);
});

答案 3 :(得分:1)
我认为,如果你想使用try...catch
块,你需要抛出一些东西才能进入catch
部分。你可以使用几乎所有失败的错误(如其他帖子中提到的那样)。
如果在某些时候,你想要 run-or-die 而不必亲自编写throw语句,你总是可以做一个断言:
const myFunction = () => {
try {
assert.fail();
console.log(`Did not work :)`);
} catch (e) {
console.log(`OK`);
}
};
当然,我宁愿尝试断言积极的东西(更多的禅宗),我需要继续。
答案 4 :(得分:1)
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