在 JavaScript 中尝试 {} 而不捕获 {} 可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5764107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try {} without catch {} possible in JavaScript?
提问by pimvdb
I have a number of functions which either return something or throw an error. In a main function, I call each of these, and would like to return the value returned by each function, or go on to the second function if the first functions throws an error.
我有许多函数要么返回一些东西要么抛出一个错误。在主函数中,我调用了其中的每一个,并希望返回每个函数返回的值,或者如果第一个函数抛出错误,则继续执行第二个函数。
So basically what I currently have is:
所以基本上我目前拥有的是:
function testAll() {
try { return func1(); } catch(e) {}
try { return func2(); } catch(e) {} // If func1 throws error, try func2
try { return func3(); } catch(e) {} // If func2 throws error, try func3
}
But actually I'd like to only try
to return it (i.e. if it doesn't throw an error). I do not need the catch
block. However, code like try {}
fails because it is missing an (unused) catch {}
block.
但实际上我只想try
返回它(即如果它不抛出错误)。我不需要catch
块。但是,像这样的代码会try {}
失败,因为它缺少一个(未使用的)catch {}
块。
I put an example on jsFiddle.
So, is there any way to have those catch
blocks removed whilst achieving the same effect?
那么,有没有办法catch
在达到相同效果的同时移除这些块?
采纳答案by ThiefMaster
No. You have to keep them.
不,你必须保留它们。
This actually makes sense since errors shouldn't be silently ignored at all.
这实际上是有道理的,因为根本不应该默默地忽略错误。
回答by kennebec
A trywithout a catchclause sends its error to the next higher catch, or the window, if there is no catch defined within that try.
一个 尝试没有赶上条款将其错误到下一个更高的渔获,或窗口,如果没有试图内定义的渔获物。
If you do not have a catch, a try expression requires a finallyclause.
如果您没有catch,则 try 表达式需要finally子句。
try {
// whatever;
} finally {
// always runs
}
回答by Dan Dascalescu
It's possible to have an empty catch block, without an error variable, starting with ES2019. This is called optional catch bindingand was implemented in V8 v6.6, released in June 2018. The feature has been available since Node 10, Chrome 66, Firefox 58, Opera 53and Safari 11.1.
从ES2019开始,可以有一个空的 catch 块,没有错误变量。这称为可选的 catch 绑定,并在 2018 年 6 月发布的 V8 v6.6中实现。该功能从Node 10、Chrome 66、Firefox 58、Opera 53和Safari 11.1开始可用。
The syntax is shown below:
语法如下所示:
try {
throw new Error("This won't show anything");
} catch { };
You still need a catch
block, but it can be empty and you don't need to pass any variable. If you don't want a catch block at all, you can use the try
/finally
, but note that it won't swallow errors as an empty catch does.
你仍然需要一个catch
块,但它可以是空的,你不需要传递任何变量。如果您根本不需要 catch 块,则可以使用try
/ finally
,但请注意,它不会像空 catch 那样吞下错误。
try {
throw new Error("This WILL get logged");
} finally {
console.log("This syntax does not swallow errors");
}
回答by alex
Nope, catch
(or finally
) is try
's friend and always there as part of try/catch.
不,catch
(或finally
)是try
的朋友,并且作为try/catch 的一部分始终存在。
However, it is perfectly valid to have them empty, like in your example.
但是,让它们为空是完全有效的,就像在您的示例中一样。
In the comments in your example code (If func1 throws error, try func2), it would seem that what you really want to do is call the next function inside of the catch
block of the previous.
在您的示例代码中的注释中(如果 func1 抛出错误,请尝试 func2),看起来您真正想要做的是调用前一个catch
块内的下一个函数。
回答by Joe B.
I wouldn't recommend try-finally without the catch, because if both the try block and finally block throw errors, the error thrown in the finally clause gets bubbled up and the try block's error is ignored, in my own test:
我不推荐没有 catch 的 try-finally,因为如果 try 块和 finally 块都抛出错误,finally 子句中抛出的错误就会冒泡,并且在我自己的测试中忽略 try 块的错误:
try {
console.log('about to error, guys!');
throw new Error('eat me!');
} finally {
console.log ('finally, who cares');
throw new Error('finally error');
}
Result:
结果:
> about to error, guys!
> finally, who cares
> .../error.js:9
> throw new Error('finally error');
> ^
>
> Error: finally error
回答by Tank
If you only want functions 2 and 3 to fire if an error occurs why are you not putting them in the catch block?
如果您只想在发生错误时触发函数 2 和 3,为什么不将它们放入 catch 块中?
function testAll() {
try {
return func1();
} catch(e) {
try {
return func2();
} catch(e) {
try {
return func3();
} catch(e) {
// LOG EVERYTHING FAILED
}
}
}
}
回答by user1800957
I've decide to look at the problem presented from a different angle.
我决定从不同的角度看待这个问题。
I've been able to determine a way to to allow closely for the code pattern requested while in part addressing the un-handled error object listed by another commenter.
我已经能够确定一种方法来密切允许所请求的代码模式,同时部分解决另一个评论者列出的未处理的错误对象。
code can be seen @ http://jsfiddle.net/Abyssoft/RC7Nw/4/
代码可见@http://jsfiddle.net/Abyssoft/RC7Nw/4/
try:catch is placed within a for loop allowing graceful fall through. while being able to iterate through all the functions needed. when explicit error handling is needed additional function array is used. in the even of error and functional array with error handlers element is not a function, error is dumped to console.
try:catch 被放置在一个 for 循环中,允许优雅地通过。同时能够遍历所需的所有功能。当需要显式错误处理时,使用额外的函数数组。即使错误和带有错误处理程序元素的函数数组不是函数,错误也会转储到控制台。
Per requirements of stackoverflow here is the code inline [edited to make JSLint compliant (remove leading spaces to confirm), improve readability]
这里根据stackoverflow的要求是内联代码[编辑以使JSLint兼容(删除前导空格以确认),提高可读性]
function func1() {"use strict"; throw "I don't return anything"; }
function func2() {"use strict"; return 123; }
function func3() {"use strict"; throw "I don't return anything"; }
// ctr = Code to Run <array>, values = values <array>,
// eh = error code can be blank.
// ctr and params should match 1 <-> 1
// Data validation not done here simple POC
function testAll(ctr, values, eh) {
"use strict";
var cb; // cb = code block counter
for (cb in ctr) {
if (ctr.hasOwnProperty(cb)) {
try {
return ctr[cb](values[cb]);
} catch (e) {
if (typeof eh[cb] === "function") {
eh[cb](e);
} else {
//error intentionally/accidentially ignored
console.log(e);
}
}
}
}
return false;
}
window.alert(testAll([func1, func2, func3], [], []));
?
?
回答by duffymo
They go together in every language that I know that has them (JavaScript, Java, C#, C++). Don't do it.
它们以我所知道的每种语言(JavaScript、Java、C#、C++)一起使用。不要这样做。
回答by Itay Merchav
I believe you need to use helper function like:
我相信您需要使用辅助功能,例如:
function tryIt(fn, ...args) {
try {
return fn(...args);
} catch {}
}
and use it like:
并使用它:
tryIt(function1, /* args if any */);
tryIt(function2, /* args if any */);
回答by Hitesh Prajapati
try & catch are like 2 side of one coin. so not possible without try.
try & catch 就像一枚硬币的两面。所以没有尝试是不可能的。