【问题标题】:Avoiding an empty catch clause避免空的 catch 子句
【发布时间】:2014-10-23 20:40:49
【问题描述】:

我有一个函数可以检查用户是否进行了任何更改,如果是,则警告他们这一事实。当他们选择放弃他们的更改时,我有另一个函数 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 的结果?

【问题讨论】:

  • 哎呀,我觉得我想多了。感谢您的快速回复。

标签: javascript try-catch-finally


【解决方案1】:

您可以使用finally 块:

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

}

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

【讨论】:

  • 看到这些回复后,我意识到我上面的模型有缺陷,因为当window.onerror 被调用时,它没有收到任何参数。如果我没有 catch 块,会调用 window.onerror 吗? (或者甚至可能有一个 catch 块?)
  • @AmadeusDrZaius - 如果脚本生成错误,将调用window.onerror。如果您在脚本中捕捉到错误,那么window.onerror 和默认事件处理程序都不会被调用(除非您重新抛出错误)。
【解决方案2】:

如果您不想要 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();
}

正如您在specification 中所见,try 语句由try 后跟catchfinally 或两者组成。

【讨论】:

    猜你喜欢
    • 2011-07-23
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多