本文介绍了Javascript尝试... catch ... else ...最后像Python,Java,Ruby等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Javascript如何复制四部分尝试
- catch
- else
- 最后
其他语言支持的执行模型?
一个清晰的简短摘要来自。在Javascript术语中:
// XXX此示例是语法错误
尝试{
//受保护-block
} catch(e){
// Handler-block
} else {
// Else-block
} finally {
//最终区块
}
受保护区块中的代码被执行。如果代码抛出异常,则执行 Handler-block ;如果没有抛出异常,则执行 Else-block 。
无论以前发生了什么, Final-block 在代码块完成并处理任何抛出的异常后执行。即使处理程序块或 Else-block 出现错误并引发新的异常, Final-block 中的代码仍会运行。
请注意,在受保护区块结尾处剪切 Else-block 并粘贴错误。如果 Else-block 中发生错误,则处理程序块 class =h2_lin>解决方案
将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();
}
};
然后我们可以像这样使用它(非常类似于python方式):
try_catch_else_finally(function(){
// protected block
},function(){
// handler block
},function(){
// else block
},function(){
// final-block
});
How can Javascript duplicate the four-part try
-catch
-else
-finally
execution model that other languages support?
A clear, brief summary is from the Python 2.5 what's new. In Javascript terms:
// XXX THIS EXAMPLE IS A SYNTAX ERROR
try {
// Protected-block
} catch(e) {
// Handler-block
} else {
// Else-block
} finally {
// Final-block
}
The code in Protected-block is executed. If the code throws an exception, Handler-block is executed; If no exception is thrown, Else-block is executed.
No matter what happened previously, Final-block is executed once the code block is complete and any thrown exceptions handled. Even if there’s an error in Handler-block or Else-block and a new exception is raised, the code in Final-block is still run.
Note that cutting Else-block and pasting at the end of Protected-block is wrong. If an error happens in Else-block, it must not be handled by Handler-block.
解决方案
Extending the idea of jhs a little, the whole concept could be put inside a function, to provide even more readability:
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):
try_catch_else_finally(function() {
// protected block
}, function() {
// handler block
}, function() {
// else block
}, function() {
// final-block
});
这篇关于Javascript尝试... catch ... else ...最后像Python,Java,Ruby等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!