条件catch子句 - 浏览器支持

Sha*_*dow 13 javascript exception

哪些浏览器支持Conditional catch子句

在MDN上尝试...捕获您可以找到条件捕获子句作为非标准功能.

try {
    myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
    // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
    // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
    // statements to handle EvalError exceptions
} catch (e) {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
}
Run Code Online (Sandbox Code Playgroud)

注意:此功能不是ECMAScript规范的一部分.

它受到任何现代浏览器的支持吗?

谷歌Chrome的控制台返回 Uncaught SyntaxError: Unexpected token if

或者我用的是:

try {
    myroutine(); // may throw three exceptions
} catch (e) {
    if(e instanceof TypeError) {
        // statements to handle TypeError exceptions
    }
    else if(e instanceof RangeError) {
        // statements to handle RangeError exceptions
    }
    else if(e instanceof EvalError) {
        // statements to handle EvalError exceptions
    }
    else {
        // statements to handle any unspecified exceptions
        logMyErrors(e); // pass exception object to error handler
    }
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*nil 5

您应该使用后者,因为它适用于所有地方,引用MDN

以下是如何使用符合ECMAScript规范的简单JavaScript实现相同的"条件捕获子句"(显然它更冗长,但无处不在(我在Firefox,IE和Chrome上测试过)),我有:

try {
    myroutine(); // may throw three types of exceptions
} catch (e) {
    if (e instanceof TypeError) {
        // statements to handle TypeError exceptions
    } else if (e instanceof RangeError) {
        // statements to handle RangeError exceptions
    } else if (e instanceof EvalError) {
        // statements to handle EvalError exceptions
    } else {
       // statements to handle any unspecified exceptions
       logMyErrors(e); // pass exception object to error handler
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个catch (e if e instanceof ..)只适用于Mozilla Firefox,并在chrome和IE上出错

Uncaught SyntaxError: Unexpected token if
Run Code Online (Sandbox Code Playgroud)

IE

SCRIPT1006: Expected ')'
Run Code Online (Sandbox Code Playgroud)


php*_*_qq 4

\n

在 MDN try...catch 上,您可以找到条件 catch 子句作为非标准功能。\n\xc2\xa0

\n\n

注意:此功能不是 ECMAScript 规范的一部分。

\n
\n\n

这意味着这不是所有浏览器和其他东西都同意可用的 javascript 语言的一部分。这肯定意味着并非所有浏览器都支持它(如果有的话)。关于跨浏览器解决方案的最佳选择是使用 switch 子句的第二种情况。GL

\n