瀏覽代碼

LibJS: Allow try statement with only finally clause

This was a regression introduced by 9ffe45b - a TryStatement without
'catch' clause *is* allowed, if it has a 'finally' clause. It is now
checked properly that at least one of both is present.
Linus Groh 4 年之前
父節點
當前提交
d6f8c52245
共有 2 個文件被更改,包括 16 次插入1 次删除
  1. 7 1
      Libraries/LibJS/Parser.cpp
  2. 9 0
      Libraries/LibJS/Tests/try-catch-finally.js

+ 7 - 1
Libraries/LibJS/Parser.cpp

@@ -1443,7 +1443,10 @@ NonnullRefPtr<TryStatement> Parser::parse_try_statement()
     consume(TokenType::Try);
 
     auto block = parse_block_statement();
-    auto handler = parse_catch_clause();
+
+    RefPtr<CatchClause> handler;
+    if (match(TokenType::Catch))
+        handler = parse_catch_clause();
 
     RefPtr<BlockStatement> finalizer;
     if (match(TokenType::Finally)) {
@@ -1451,6 +1454,9 @@ NonnullRefPtr<TryStatement> Parser::parse_try_statement()
         finalizer = parse_block_statement();
     }
 
+    if (!handler && !finalizer)
+        syntax_error("try statement must have a 'catch' or 'finally' clause");
+
     return create_ast_node<TryStatement>(move(block), move(handler), move(finalizer));
 }
 

+ 9 - 0
Libraries/LibJS/Tests/try-catch-finally.js

@@ -161,3 +161,12 @@ test("try/catch/finally with exception in try, catch and finally", () => {
     expect(catchHasBeenExecuted).toBeTrue();
     expect(finallyHasBeenExecuted).toBeTrue();
 });
+
+test("try statement must have either 'catch' or 'finally' clause", () => {
+    expect("try {} catch {}").toEval();
+    expect("try {} catch (e) {}").toEval();
+    expect("try {} finally {}").toEval();
+    expect("try {} catch {} finally {}").toEval();
+    expect("try {} catch (e) {} finally {}").toEval();
+    expect("try {}").not.toEval();
+});