避免使用空的catch子句

Avoiding an empty catch clause

本文关键字:catch 子句      更新时间:2023-09-26

我有一个函数,它检查用户是否进行了任何更改,如果进行了更改,就会警告他们这一事实。当他们选择放弃更改时,我有另一个功能,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块对我来说似乎是一种代码气味,但我不认为这种方式一定更好。(但也许是这样。)

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块:

function cancelEdit() {
    try {
        // destroy editing boxes
        // [code goes here]
    } finally {
        cancelEditInternal();
    }
}

无论try的主体是否抛出错误,都将执行finally块。(如果保留catch子句,finally块仍将执行。)

如果您不想要catch块,那么就不要使用它:

try {
    // destroy editing boxes
    // [code goes here]
} 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();
}

正如您在规范中所看到的,try语句由trycatchfinally组成,或者两者都有。