Why brackets are necessary in catch block in java?
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?
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.
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 { }.
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.