jls - Why do try/catch or synchronized in Java require a statement block? -


java allows keywords followed statement or statement block. example:

if (true)     system.out.println("true");      system.out.println("true"); while (true); 

compiles as

if(true) {     system.out.println("true"); }  {    system.out.println("true"); } while (true); 

this true keywords for, while etc.

however, keywords don't allow this. synchronized requires block statement. same try ... catch ... finally, requires @ least 2 block statements following keywords. example:

try {     system.out.println("try"); } {     system.out.println("finally"); }  synchronized(this) {     system.out.println("synchronized"); } 

works, following doesn't compile:

try     system.out.println("try");     system.out.println("finally");  synchronized (this)     system.out.println("synchronized"); 

so why keywords in java require block statement, while others allow block statement single statement? inconsistency in language design, or there reason this?

you dangling else-like ambiguity if try allow leaving out braces. whilst solved in similar fashion dangling-else, best not to.

consider

try try  fn(); catch (gexception exc) g(); catch (hexception exc) h(); catch (iexception exc) i(); 

does mean

try     try          fn();     catch (gexception exc)         g();     catch (hexception exc)         h(); catch (iexception exc)     i(); 

or

try     try          fn();     catch (gexception exc)         g(); catch (hexception exc)     h(); catch (iexception exc)     i(); 

i believe in clu, catch blocks around 1 statement (may wrong).


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -