Javascript try...catch...else...最终喜欢 Python、Java、Ruby 等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4872170/
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
Javascript try...catch...else...finally like Python, Java, Ruby, etc
提问by JasonSmith
How can Javascript duplicate the four-part try-catch-else-finallyexecution model that other languages support?
Javascript 如何复制其他语言支持的四部分try- catch- else-finally执行模型?
A clear, brief summary is from the Python 2.5 what's new. In Javascript terms:
一个清晰、简短的总结来自Python 2.5 what's new。在 Javascript 术语中:
// XXX THIS EXAMPLE IS A SYNTAX ERROR
try {
// Protected-block
} catch(e) {
// Handler-block
} else {
// Else-block
} finally {
// Final-block
}
The code in Protected-blockis executed. If the code throws an exception, Handler-blockis executed; If no exception is thrown, Else-blockis executed.
Protected-block 中的代码被执行。如果代码抛出异常,则执行Handler-block;如果没有抛出异常,则执行Else-block。
No matter what happened previously, Final-blockis executed once the code block is complete and any thrown exceptions handled. Even if there's an error in Handler-blockor Else-blockand a new exception is raised, the code in Final-blockis still run.
无论之前发生了什么,一旦代码块完成并处理了任何抛出的异常,就会执行Final-block。即使Handler-block或Else-block出现错误并引发新的异常,Final-block 中的代码仍会运行。
Note that cutting Else-blockand pasting at the end of Protected-blockis wrong. If an error happens in Else-block, it must notbe handled by Handler-block.
请注意,将Else-block剪切并粘贴到Protected-block末尾是错误的。如果Else-block 中发生错误,则Handler-block不得处理。
采纳答案by Jakob
Extending the idea of jhs a little, the whole concept could be put inside a function, to provide even more readability:
稍微扩展 jhs 的想法,整个概念可以放在一个函数中,以提供更多的可读性:
var try_catch_else_finally = function(protected_code, handler_code, else_code, finally_code) {
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
finally_code();
}
};
Then we can use it like this (very similar to the python way):
然后我们就可以这样使用了(非常类似于python的方式):
try_catch_else_finally(function() {
// protected block
}, function() {
// handler block
}, function() {
// else block
}, function() {
// final-block
});
回答by cbarrick
I know this is old, but here is a pure syntax solution, which I think is the proper way to go:
我知道这是旧的,但这是一个纯语法解决方案,我认为这是正确的方法:
try {
// Protected-block
try {
// Else-block
} catch (e) {
// Else-handler-block
}
} catch(e) {
// Handler-block
} finally {
// Final-block
}
The code in Protected-blockis executed. If the code throws an error, Handler-blockis executed; If no error is thrown, Else-blockis executed.
Protected-block 中的代码被执行。如果代码抛出错误,则执行Handler-block;如果没有抛出错误,则执行Else-block。
No matter what happened previously, Final-blockis executed once the code block is complete and any thrown errors handled. Even if there's an error in Handler-blockor Else-block, the code in Final-blockis still run.
无论之前发生了什么,一旦代码块完成并处理了任何抛出的错误,就会执行Final-block。即使Handler-block或Else-block 中出现错误,Final-block 中的代码仍会运行。
If an error is thrown in the Else-blockit is nothandled by the Handler-blockbut instead by the Else-handler-block
如果在Else-block 中抛出错误,则不会由Handler-block处理,而是由Else-handler-block 处理
And if you know that the Else-blockwill not throw:
如果你知道Else 块不会抛出:
try {
// Protected-block
// Else-block
} catch(e) {
// Handler-block
} finally {
// Final-block
}
Moral of the story, don't be afraid to indent ;)
故事的寓意,不要害怕缩进;)
Note:this works only if the Else-handler-blocknever throws.
注意:这仅在Else-handler-block从不抛出时才有效。
回答by JasonSmith
Javascript does not have the syntax to support the no-exception scenario. The best workaround is nested trystatements, similar to the "legacy" technique from PEP 341
Javascript 没有支持无异常情况的语法。最好的解决方法是嵌套try语句,类似于PEP 341 中的“遗留”技术
// A pretty-good try/catch/else/finally implementation.
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
this_always_runs();
}
Besides readability, the only problem is the successvariable. If protected_codesets window.success = false, this will not work. A less readable but safer way uses a function namespace:
除了可读性之外,唯一的问题是success变量。如果protected_code设置window.success = false,这将不起作用。一种不太可读但更安全的方法是使用函数命名空间:
// A try/catch/else/finally implementation without changing variable bindings.
try {
(function() {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
})();
} finally {
this_always_runs();
}
回答by jaheraho
I know the question is old and answers has already given but I think that my answer is the simplest to get an "else" in javascripts try-catch-block.
我知道这个问题很旧,答案已经给出,但我认为我的答案是在 javascripts try-catch-block 中获得“else”的最简单方法。
var error = null;
try {
/*Protected-block*/
} catch ( catchedError ) {
error = catchedError; //necessary to make it available in finally-block
} finally {
if ( error ) {
/*Handler-block*/
/*e.g. console.log( 'error: ' + error.message );*/
} else {
/*Else-block*/
}
/*Final-block*/
}
回答by Mitra Ardron
Here's another solution if the problem is the common one of not wanting the error callback to be called if there is an uncaught error thrown by the first callback. ... i.e. conceptually you want ...
如果问题是第一个回调引发未捕获的错误时不希望调用错误回调的常见问题,那么这是另一种解决方案。... 即概念上你想要 ...
try {
//do block
cb(null, result);
} catch(err) {
// err report
cb(err)
}
But an error in the success cb causes the problem of cb getting called a second time. So instead I've started using
但是成功 cb 中的错误会导致 cb 被第二次调用的问题。所以我开始使用
try {
//do block
try {
cb(null, result);
} catch(err) {
// report uncaught error
}
} catch(err) {
// err report
cb(err)
}
which is a variant on @cbarrick's solution.
这是@cbarrick 解决方案的一个变体。

