JavaScript 嵌套尝试异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28929500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:46:46  来源:igfitidea点击:

JavaScript nested try exception

javascriptexceptionexception-handling

提问by Robert Rocha

I am reading up on JavaScript exceptions:

我正在阅读 JavaScript异常

You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is checked for a match.

您可以嵌套一个或多个 try...catch 语句。如果内部 try...catch 语句没有 catch 块,则会检查封闭的 try...catch 语句的 catch 块是否匹配。

I think I understood it correctly and wrote this test code as follows:

我想我理解正确,写了这个测试代码如下:

try {

    try {
        throw "error";
    }

} catch( e ) {

    console.log( e );

}

But got this error:

但是得到了这个错误:

Uncaught SyntaxError: Missing catch or finally after try

Uncaught SyntaxError: Missing catch or finally after try

I know it clearly says that I am missing a catch or finally but the JavaScript documentation says my code should be valid or am I misunderstanding?

我知道它清楚地表明我错过了一个问题或最后但 JavaScript 文档说我的代码应该是有效的还是我误解了?

回答by T.J. Crowder

The quoted text is quite misleading because it says "if an inner try..catch doesn't have a catch block" which doesn't make any sense. It should just be "if an inner trydoesn't have...".

引用的文本非常具有误导性,因为它说“如果内部 try..catch 没有 catch 块”,这没有任何意义。它应该只是“如果内部try没有......”。

In JavaScript, you can't just have a tryon its own; it hasto have a catch, finally, or both. So the scenario that quote is referring so isa try/catchcontaining a try/finally(not another try/catch):

在 JavaScript 中,您不能只拥有一个try;它有一个catchfinally或两者兼而有之。所以引用所指的场景所以 isatry/catch包含一个try/finally(不是另一个try/catch):

try {
    try {
        throw "error";
    }
    finally {
    }
} catch( e ) {
    console.log( e );
}

回答by Gaurav Kakkar

It is specified here: (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/try...catch)

它在此处指定:(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/try...catch

The try statement consists of a try block, which contains one or more statements, and at least one catch clause or a finally clause, or both. That is, there are three forms of the try statement:

try 语句由包含一个或多个语句的 try 块和至少一个 catch 子句或 finally 子句或两者组成。也就是说,try语句有以下三种形式: