For Programmers: Free Programming Magazines  


Home > Archive > Java Help > May 2004 > Re: {} vs {;}









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: {} vs {;}
Amedee Van Gasse

2004-05-12, 7:55 pm

"Homer Fong" <homer_fong@hotmail.com> wrote in news:RfjRb.1203$qR3.782
@bignews3.bellsouth.net:

> Is there any difference between {} and {;} when writing an empty catch
> block?
>
> example:
> try { in.close(); } catch (IOException ignore) {}
> -vs-
> try { in.close(); } catch (IOException ignore) {;}
>
> Thanks for any input.
>
> Homer
>
>


....
catch (Exception e) {
e.printStackTrace();
}

could be useful when debugging...

--
Amedee
KC Wong

2004-05-12, 7:55 pm

> > Is there any difference between {} and {;} when writing an empty catch[color=darkred]

No. And you can put any number of semi-colons in your code, where the spaces
and newlines are.
But I consider any empty catch blocks a really bad style. Even if you
expected the code the throw a certain exception sometimes, at least put a
comment in there to explain why you do nothing.


Tony Morris

2004-05-12, 7:55 pm


"Amedee Van Gasse" <amedee@amedee.doesnotwantspam.be> wrote in message
news:Xns94E77D2CA1607amedeeamedeedoesnot
w@195.130.132.70...
> "Homer Fong" <homer_fong@hotmail.com> wrote in news:RfjRb.1203$qR3.782
> @bignews3.bellsouth.net:
>
>
> ...
> catch (Exception e) {
> e.printStackTrace();
> }
>
> could be useful when debugging...
>
> --
> Amedee


One is horribly ugly.
The other is electing yourself as candidate for some painful torture
treatment.
Is there a difference ? No, not really.

NEVER EVER have an empty catch block. EVER! NO, NEVER!
ESCPECIALLY (how can you put extra emphasis on top of NEVER?), when abusing
the exception handling mechanism by declaring to catch java.lang.Exception
without rethrowing.

I see this kind of fugliness all too often, and somebody will be plotting to
cause you great discomfort if they ever have to pay the consquences of your
poorly written code (I know this, because I plot these things myself).

On a more trivial note, if you really feel the need to place semi-colons
throughout your code (aka "empty statements"), feel free to do so. I don't
think the reader of your code will be any less pleased by a few arbitrary
empty statements thrown around in an ad hoc fashion to achieve nothing. In
much the same way that I wouldn't be less pleased if I stood in a dog poo,
if I was already covered in it.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)


Eric Sosman

2004-05-12, 7:55 pm

Tony Morris wrote:
>
> NEVER EVER have an empty catch block. EVER! NO, NEVER!
> ESCPECIALLY (how can you put extra emphasis on top of NEVER?), when abusing
> the exception handling mechanism by declaring to catch java.lang.Exception
> without rethrowing.
>
> I see this kind of fugliness all too often, and somebody will be plotting to
> cause you great discomfort if they ever have to pay the consquences of your
> poorly written code (I know this, because I plot these things myself).


As a relative newbie, I have on occasion written empty
catch blocks -- and it seems to me that at least some of them
are defensible. For example, one of my fumbling efforts has
a simple GUI, in which I try to position and size the JFrame
the same way the user left it on the prior execution; this is
recorded in a Preferences object. There's always the chance
that the Preferences might contain garbage or no value, so I
write (paraphrased):

try {
int xlft = Integer.parseInt(prefs.get("XLFT", ""));
int ytop = Integer.parseInt(prefs.get("YTOP", ""));
int wide = Integer.parseInt(prefs.get("WIDE", ""));
int tall = Integer.parseInt(prefs.get("TALL", ""));
frame.setBounds(xlft, ytop, wide, tall);
}
catch (NumberFormatException ex) {
// bad data: just let the frame choose its own bounds
}

If there's a reason not to do this I'd be glad to learn of
it. And if there's a better approach you could tell me of, I'd
be gladder still.

--
Eric.Sosman@sun.com

Virgil Green

2004-05-12, 7:55 pm

"Eric Sosman" <Eric.Sosman@sun.com> wrote in message
news:40A238D6.6060900@sun.com...
> Tony Morris wrote:
abusing[color=darkred]
java.lang.Exception[color=darkred]
plotting to[color=darkred]
your[color=darkred]
>
> As a relative newbie, I have on occasion written empty
> catch blocks -- and it seems to me that at least some of them
> are defensible. For example, one of my fumbling efforts has
> a simple GUI, in which I try to position and size the JFrame
> the same way the user left it on the prior execution; this is
> recorded in a Preferences object. There's always the chance
> that the Preferences might contain garbage or no value, so I
> write (paraphrased):
>
> try {
> int xlft = Integer.parseInt(prefs.get("XLFT", ""));
> int ytop = Integer.parseInt(prefs.get("YTOP", ""));
> int wide = Integer.parseInt(prefs.get("WIDE", ""));
> int tall = Integer.parseInt(prefs.get("TALL", ""));
> frame.setBounds(xlft, ytop, wide, tall);
> }
> catch (NumberFormatException ex) {
> // bad data: just let the frame choose its own bounds
> }
>
> If there's a reason not to do this I'd be glad to learn of
> it. And if there's a better approach you could tell me of, I'd
> be gladder still.


But you didn't leave it empty. You included a comment explaining why no
action was needed. There's a difference between an empty catch phrase and
one containing no executable statements.

- Virgil


Eric Sosman

2004-05-12, 7:55 pm

Virgil Green wrote:
> "Eric Sosman" <Eric.Sosman@sun.com> wrote in message
> news:40A238D6.6060900@sun.com...
>
>
> But you didn't leave it empty. You included a comment explaining why no
> action was needed. There's a difference between an empty catch phrase and
> one containing no executable statements.


Well, that was my thought, too. But there seems to be no
standard definition of "empty," and Tony Morris described {;}
as an "empty" block (even though it *does* contain an executable
statement!), so I thought I'd ask. Don't pass up an easy chance
to learn something ...

Hmmm... Is a catch block containing ten space characters
"empty" or just "spacious?" ;-)

--
Eric.Sosman@sun.com

Bent C Dalager

2004-05-12, 7:55 pm

In article <40A25B6E.9070303@sun.com>,
Eric Sosman <Eric.Sosman@Sun.COM> wrote:
>
> Well, that was my thought, too. But there seems to be no
>standard definition of "empty," and Tony Morris described {;}
>as an "empty" block (even though it *does* contain an executable
>statement!), so I thought I'd ask. Don't pass up an easy chance
>to learn something ...
>
> Hmmm... Is a catch block containing ten space characters
>"empty" or just "spacious?" ;-)


The point must be that the catch block should contain something that
tells the reader how the exceptional condition is to be handled. If
there is code there to handle the situation, fine, that tells the
reader how things are handled. If there is a comment there explaining
why the condition is not being handled, that is fine too because it
tells the reader that no handling is necessary (and why). If it's
empty or just a semicolon or something else pointless, that tells the
reader nothing and so is rather useless.

As an example,
catch (WhatNotException ex)
{
// ignore
}
is somewhat pointless as it doesn't explain _why_ the exception is
being ignored. It is not _entirely_ pointless because at the very
least, it does tell the reader that ignoring the exception was
intentional rather than accidental.

Cheers
Bent D
--
Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd
powered by emacs
Virgil Green

2004-05-12, 7:55 pm

"Eric Sosman" <Eric.Sosman@sun.com> wrote in message
news:40A25B6E.9070303@sun.com...
> Virgil Green wrote:
and[color=darkred]
>
> Well, that was my thought, too. But there seems to be no
> standard definition of "empty," and Tony Morris described {;}
> as an "empty" block (even though it *does* contain an executable
> statement!), so I thought I'd ask. Don't pass up an easy chance
> to learn something ...


It is devoid of information.

> Hmmm... Is a catch block containing ten space characters
> "empty" or just "spacious?" ;-)


See above.

- Virgil


Shane Mingins

2004-05-13, 1:32 am

"Eric Sosman" <Eric.Sosman@sun.com> wrote in message
news:40A238D6.6060900@sun.com...
> As a relative newbie, I have on occasion written empty
> catch blocks -- and it seems to me that at least some of them
> are defensible. For example, one of my fumbling efforts has
> a simple GUI, in which I try to position and size the JFrame
> the same way the user left it on the prior execution; this is
> recorded in a Preferences object. There's always the chance
> that the Preferences might contain garbage or no value, so I
> write (paraphrased):
>
> try {
> int xlft = Integer.parseInt(prefs.get("XLFT", ""));
> int ytop = Integer.parseInt(prefs.get("YTOP", ""));
> int wide = Integer.parseInt(prefs.get("WIDE", ""));
> int tall = Integer.parseInt(prefs.get("TALL", ""));
> frame.setBounds(xlft, ytop, wide, tall);
> }
> catch (NumberFormatException ex) {
> // bad data: just let the frame choose its own bounds
> }
>
> If there's a reason not to do this I'd be glad to learn of
> it. And if there's a better approach you could tell me of, I'd
> be gladder still.
>
> --
> Eric.Sosman@sun.com
>



Been thinking, how about something like this:

String x = prefs.get("XLFT", "");
String y = prefs.get("YTOP", "");
String width = prefs.get("WIDE", "");
String height = prefs.get("TALL", "");

Rectangle prefBoundary = getPreferencesBoundary(x, y, width,
height);
if (prefBoundary != null) frame.setBounds(prefBoundary);

private Rectangle getPreferencesBoundary(String x, String y, String
width, String height)
{
Rectangle result = null;

if (isNumber(x) && isNumber(y) && isNumber(width) &&
isNumber(height))
{
result = new Rectangle(Integer.parseInt(x), Integer.parseInt(y),
Integer.parseInt(width),
Integer.parseInt(height));
}

return result;
}

private boolean isNumber(String s)
{
try
{
Integer.parseInt(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}


And if you could determine the default boundary then getPreferences could
return the default in the event that the preferences are "garbage" and then
the test for null disappears and you simply type

frame.setBounds(getPreferencesBoundary(x, y, width, height));


Does that make the code express it's intent better or not?

I know it does not remove the use of the try/catch ... I have not seen an
alternative to testing Strings to see if they are valid numbers. But does
my approach read better?

Cheers
Shane


--
"If you really want something in this life, you have to work for it - Now
quiet, they're about to announce the lottery numbers!"


Eric Sosman

2004-05-13, 12:41 pm

Shane Mingins wrote:
>
> Been thinking, how about something like this:
> [snipped; see up-thread]
>
> Does that make the code express it's intent better or not?
>
> I know it does not remove the use of the try/catch ... I have not seen an
> alternative to testing Strings to see if they are valid numbers. But does
> my approach read better?


Personally, I find five "working" lines wrapped in a try/catch
more pleasant to read than sixteen working lines scattered across
three methods with two try/catch blocks (you wrote only one, but
I think the compiler will complain until another is inserted).

Beauty is in the eye of the beholder, of course. On the other
hand, brevity is the soul of wit ...

--
Eric.Sosman@sun.com

steve

2004-05-16, 7:31 pm

On Thu, 13 May 2004 01:24:25 +0800, Bent C Dalager wrote
(in article <c7tmk9$501$1@orkan.itea.ntnu.no> ):

> In article <40A25B6E.9070303@sun.com>,
> Eric Sosman <Eric.Sosman@Sun.COM> wrote:
>
> The point must be that the catch block should contain something that
> tells the reader how the exceptional condition is to be handled. If
> there is code there to handle the situation, fine, that tells the
> reader how things are handled. If there is a comment there explaining
> why the condition is not being handled, that is fine too because it
> tells the reader that no handling is necessary (and why). If it's
> empty or just a semicolon or something else pointless, that tells the
> reader nothing and so is rather useless.
>
> As an example,
> catch (WhatNotException ex)
> {
> // ignore
> }
> is somewhat pointless as it doesn't explain _why_ the exception is
> being ignored. It is not _entirely_ pointless because at the very
> least, it does tell the reader that ignoring the exception was
> intentional rather than accidental.
>
> Cheers
> Bent D
>


personally I never use an empty catch block, i always re-direct to my own
error handler/logger.
along the lines of myError((Exception)exception,(int )Level);

where level = an int , which i generally initialize as:
0=ignore;
1=critical;
..........
...

At least that way by changing my error handler setup ( via an info file, that
downloads to the client from a central database ( when a user reports an
error))
I can log EVERY Exception that I thought I wanted to be silent, instead of
playing "hunt the empty exception handler"
( sort of remote debugging extreme style)

There must be a reason for a try to fail, and if it can be coded around , by
extra checks then so be it.
once the exception has been fired we are already wasting a load of time, so
we may as well do something with the time and information.

It also adds to my piece of mind, when a user reports an error , I never have
to wonder if it was one of my empty exception handlers having a knock on
effect.

so the answer would be "DON'T DO Either, you lazy programmers"

steve






Josef Garvi

2004-05-18, 9:35 am

steve wrote:

> personally I never use an empty catch block, i always re-direct to my own
> error handler/logger.
> along the lines of myError((Exception)exception,(int )Level);


Wouldn't that create a lot of dependancies for your classes?
Any class you write will need to import MyError...

--
Josef Garvi

"Reversing desertification through drought tolerant trees"
http://www.eden-foundation.org/

new income - better environment - more food - less poverty
KC Wong

2004-05-18, 10:32 pm

> > personally I never use an empty catch block, i always re-direct to my
own
>
> Wouldn't that create a lot of dependancies for your classes?
> Any class you write will need to import MyError...


What's wrong with that? That's his code, of course he can use his own error
logger. And if you have written a good, flexible, easy-to-use error logger,
why shouldn't you use it?


Josef Garvi

2004-05-19, 4:31 am

KC Wong wrote:

>
> own
>
>
>
> What's wrong with that? That's his code, of course he can use his own error
> logger. And if you have written a good, flexible, easy-to-use error logger,
> why shouldn't you use it?


Well, thinking in terms of code reuse, it means that he will need to link
all his code to his particular error logger. Or have all his classes take
an error logger interface as parameter. If he would want to share his code
with other programmers or use it in other types of projects, it would be
hard to lift the code.

Of course, I realise it is Steve's code and did not mean my comment as a
criticism towards him, but more as a general question about design
principles. He has done a flexible solution by calling a class that checks
an info file before (my understanding) dynamically linking to a logger
class. That's neat, but will only work in his environment. If one has code
reuse in mind, then this looks like too tight coupling to me. Otherwise, I
agree that logging the exceptions instead of leaving them silent is a good
practice.

I wonder in what respect Aspect-Orientation would help solve this problem...

--
Josef Garvi

"Reversing desertification through drought tolerant trees"
http://www.eden-foundation.org/

new income - better environment - more food - less poverty
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com