为什么Java中的try/catch或synchronized需要语句块?

Bob*_*Bob 9 java jls

Java允许某些关键字后跟语句或语句块.例如:

if (true)
    System.out.println("true");

do
    System.out.println("true");
while (true);
Run Code Online (Sandbox Code Playgroud)

编译以及

if(true) {
    System.out.println("true");
}

do {
   System.out.println("true");
} while (true);
Run Code Online (Sandbox Code Playgroud)

这也适用于像关键字for,while等等.

但是,有些关键字不允许这样做.synchronized需要一个块语句.相同try ... catch ... finally,这需要在关键字后面至少有两个块语句.例如:

try {
    System.out.println("try");
} finally {
    System.out.println("finally");
}

synchronized(this) {
    System.out.println("synchronized");
}
Run Code Online (Sandbox Code Playgroud)

有效,但以下内容无法编译:

try
    System.out.println("try");
finally
    System.out.println("finally");

synchronized (this)
    System.out.println("synchronized");
Run Code Online (Sandbox Code Playgroud)

那么为什么Java中的某些关键字需要块语句,而其他关键字允许块语句以及单个语句?这是语言设计的不一致,还是有某种原因?

Tom*_*ine 4

如果你试图允许省略大括号,你会得到一个类似其他的悬而未决的歧义。虽然这可以通过与悬空其他类似的方式解决,但最好不要这样做。

考虑

try
try 
fn();
catch (GException exc)
g();
catch (HException exc)
h();
catch (IException exc)
i();
Run Code Online (Sandbox Code Playgroud)

这是否意味着

try
    try 
        fn();
    catch (GException exc)
        g();
    catch (HException exc)
        h();
catch (IException exc)
    i();
Run Code Online (Sandbox Code Playgroud)

或者

try
    try 
        fn();
    catch (GException exc)
        g();
catch (HException exc)
    h();
catch (IException exc)
    i();
Run Code Online (Sandbox Code Playgroud)

我相信 CLU,catch 块仅围绕一个语句(可能是错误的)。