开发者

Why brackets are necessary in catch block in java?

In java if we have to execute only one statement after if or for the brackets are not necessary. We can write:

if(condition)
  executeSingleStatement();

or

for(init;condition;incr)
  开发者_如何学CexecuteSingleStatement();

But in the case of catch block why we can not omit the brackets? Why this is not possible?

catch(Exception e)
   e.printStackTrace();

Because in most of the case we I have only one statement in catch block which is either e.printStackTrace() while testing or logging statement.


Find a compiler construction textbook and look-up the dangling-else ambiguity.

Given that in Java, and most other languages with horrible syntax, spacing lies. How do you interpret:

try
try
stuff();
catch (FooException exc)
handle(exc);
catch (BarException exc)
handle(exc);
catch (BazException exc)
handle(exc);

Is it:

try {
    try {
        stuff();
    } catch (FooException exc) {
        handle(exc);
    } catch (BarException exc) {
        handle(exc);
    }
} catch (BazException exc) {
    handle(exc);
}

Or:

try {
    try {
        stuff();
    } catch (FooException exc) {
        handle(exc);
    }
} catch (BarException exc) {
    handle(exc);
} catch (BazException exc) {
    handle(exc);
}

The dangling-else ambiguity is resolved by associating the else with the inner-most if. Do we want to add a more complicated complication to handle this poor style? No.

Edit: There's a comment that the example does not cover catch. It would be a proper weird decision to require braces on try but not catch/finally. But anyway, for completeness, consider the following code.

try {
stuff();
} catch (FooException foo)
try {
handle(foo);
} catch (BarException bar)
handle(bar);
catch (BazException baz)
handle(baz);
finally
release();

Is the catch of BazException and finally associated with the inner or outer try? Again the language design committee could have added a ton of grammar to disambiguate, but again explicit style wins. My job at Sun/Oracle would have been a little easier if the language had been simplified to mandate explicit braces everywhere.


It's not an issue of possible or impossible. It's just a language (syntax) design decision.

There are several implementation of Java language parser. One could modify the parser source less than a day and allow no-bracket-enclosed catch statements.

http://www.google.com/search?q=java+parser

Also note Java language grammar.


I'm not sure why Java doesn't allow that but generally speaking it is better style to use brackets even if there is only one statement. It makes it easier to read and expand.

Here is a related question that addresses whether to use brackets or not: Are curly braces necessary in one-line statements in JavaScript?


From the Java Language Spec 3.0 - If you look at Chapter 14, it talks about Blocks and Statements. Blocks are identified by { and } and contain many statements. Try/catch/finally are blocks, which per the language spec need to be grouped in { }.


I also do not see any benefit in writing useless code and I also do not understand how more text could be easier.

I help myself by writing one-line-catches in exactly one line:

catch (InvalidArgumentException e) { die (e.getMessage()); }
catch (Exception e)                { die (e); }

For me this is the most readable way. It gets only cluttered when people try to write complete novels into exception names.

catch (CanNotPayAttentionToThatManBehindTheCurtainThrowableRuntimeExceptionWithMessageAndCouseContainItselfAnotherCourseAndMessage e) ...


I would argue that "in most cases" you should be doing more than just printing or logging the stack trace. This means you are swallowing an exception, which is not generally a good practice. At the least, if you cannot gracefully recover from the exception, you should log and rethrow it in case code higher up the stack can.

That said, I don't think there is really an answer to your question beyond "that's just how they designed it".


Probably inherited from C++. No idea why C++ did that. See my thoughts here: https://stackoverflow.com/questions/6254595/how-do-you-use-the-return/6255489#6255489

It's also worth noting that {} makes grammar simpler, i.e. makes language designer's life easier. The if statement is a good example - the convenience you like does not come cheaply.

Because of the ambiguity like

if(c1) if(c2) A; else B;

interpretation 1 
if(c1)
    if(c2) 
        A;
    else 
        B;

interpretation 2 
if(c1)
    if(c2) 
        A;
else 
    B;

The grammar of if has to be tweaked to resolve the ambiguity. Suppose block is required instead of arbitrary statement, the grammar would be much simpler because of the presence of {}.

So they were probabaly just feeling lazy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜