我有一个函数可以检查用户是否进行了任何更改,如果是,则警告他们这一事实。当他们选择放弃更改时,我有另一个函数,a)将状态恢复为预编辑,b)更新一个全局对象,该对象保存有关当前编辑的信息(包括是否存在)。
我不希望发生的是,在尝试删除编辑框元素时会引发一些错误,因此系统不会更新全局对象标志或显示隐藏的预编辑元素。如果发生这种情况,程序可能会认为编辑仍在进行,但实际上并非如此,从而使用户陷入“放弃更改?”的困境。循环。因此,我捕获在销毁阶段抛出的任何错误,然后显示隐藏元素并更新全局,如下所示:
function cancelEdit() {
try {
// destroy editing boxes
// [code goes here]
} catch(e) {
} finally {
// restore hidden elements
// [code goes here]
// update global edit cache object
// [code goes here]
// rethrow the error for analysis server-side
if(window.onerror) window.onerror();
}
}
像上面这样的空 catch block 对我来说似乎有代码味道,但我不认为这种方式一定更好。 (但也许确实如此。)
function cancelEdit() {
try {
// destroy editing boxes
// [code goes here]
} catch(e) {
cancelEditInternal();
// rethrow the error for analysis server-side
throw e;
}
cancelEditInternal();
}
function cancelEditInternal() {
// restore hidden elements
// [code goes here]
// update global edit cache object
// [code goes here]
}
我错过了什么吗?是否存在我忽略的模式...或者这只是我在通常不使用的地方使用 try/catch/finally 的结果?
最佳答案
您可以使用finally
block :
function cancelEdit() {
try {
// destroy editing boxes
// [code goes here]
} finally {
cancelEditInternal();
}
}
无论 try
的主体是否抛出错误,finally
block 都会被执行。 (如果保留 catch
子句,finally
block 仍将执行。)
关于javascript - 避免空的 catch 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26537048/