Java Forum / First Aid / May 2004
{} vs {;}
Homer Fong - 27 Jan 2004 01:38 GMT 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
Chris Smith - 27 Jan 2004 01:47 GMT > Is there any difference between {} and {;} when writing an empty catch > block? [quoted text clipped - 5 lines] > > Thanks for any input. The grammatical difference is that the first is an empty catch block, whereas the second is a catch block containing one statement, but that statement is empty. Functionally, they are identical.
As a matter of course, I'd suggest using neither. If you need an empty catch block, it should contain a comment advising that reader that this is part of some thought-out control flow, and not just someone being lazy. Just for one data point, I as a matter of course replace empty catch blocks that I find while reading code with error logging statements, and I'd hate to do so only to find that reaching the empty block was considered a normal case by the programmer who wrote the code.
 Signature www.designacourse.com The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
AdT - 27 Jan 2004 15:55 GMT when reading your code you know that you inteded your Block to be "empty" - it was not left empty by mistake.
bye
AdT
Chris Smith - 27 Jan 2004 16:15 GMT > when reading your code you know that you inteded your Block to be "empty" - > it was not left empty by mistake. In which case are you saying this? I can't see how one or the other ({} or {;}) conveys that more clearly. If it's your private convention, that's one thing, but a comment would be obvious to everyone.
 Signature www.designacourse.com The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Amedee Van Gasse - 12 May 2004 11:18 GMT "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? [quoted text clipped - 7 lines] > > Homer ... catch (Exception e) { e.printStackTrace(); }
could be useful when debugging...
 Signature Amedee
KC Wong - 12 May 2004 11:21 GMT > > Is there any difference between {} and {;} when writing an empty catch > > block? 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 - 12 May 2004 12:17 GMT > "Homer Fong" <homer_fong@hotmail.com> wrote in news:RfjRb.1203$qR3.782 > @bignews3.bellsouth.net: [quoted text clipped - 17 lines] > > could be useful when debugging... 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.
 Signature Tony Morris (BInfTech, Cert 3 I.T., SCJP[1.4], SCJD) Software Engineer IBM Australia - Tivoli Security Software (2003 VTR1000F)
Eric Sosman - 12 May 2004 15:46 GMT > NEVER EVER have an empty catch block. EVER! NO, NEVER! > ESCPECIALLY (how can you put extra emphasis on top of NEVER?), when abusing [quoted text clipped - 4 lines] > 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.
 Signature Eric.Sosman@sun.com
Virgil Green - 12 May 2004 17:30 GMT > > NEVER EVER have an empty catch block. EVER! NO, NEVER! > > ESCPECIALLY (how can you put extra emphasis on top of NEVER?), when abusing [quoted text clipped - 28 lines] > 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 - 12 May 2004 18:14 GMT >>>NEVER EVER have an empty catch block. EVER! NO, NEVER! >> [quoted text clipped - 19 lines] > 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?" ;-)
 Signature Eric.Sosman@sun.com
Bent C Dalager - 12 May 2004 18:24 GMT > Well, that was my thought, too. But there seems to be no >standard definition of "empty," and Tony Morris described {;} [quoted text clipped - 4 lines] > 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
 Signature Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd powered by emacs
steve - 16 May 2004 23:03 GMT >> Well, that was my thought, too. But there seems to be no >> standard definition of "empty," and Tony Morris described {;} [quoted text clipped - 26 lines] > 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 - 18 May 2004 13:15 GMT > 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...
 Signature Josef Garvi
"Reversing desertification through drought tolerant trees" http://www.eden-foundation.org/
new income - better environment - more food - less poverty
KC Wong - 19 May 2004 02:30 GMT > > 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... 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 - 19 May 2004 08:34 GMT >>>personally I never use an empty catch block, i always re-direct to my > [quoted text clipped - 9 lines] > 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...
 Signature Josef Garvi
"Reversing desertification through drought tolerant trees" http://www.eden-foundation.org/
new income - better environment - more food - less poverty
Virgil Green - 12 May 2004 23:33 GMT > >>>NEVER EVER have an empty catch block. EVER! NO, NEVER! > >> [quoted text clipped - 25 lines] > 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 - 13 May 2004 05:51 GMT > As a relative newbie, I have on occasion written empty > catch blocks -- and it seems to me that at least some of them [quoted text clipped - 19 lines] > it. And if there's a better approach you could tell me of, I'd > be gladder still. 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
 Signature "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 - 13 May 2004 17:00 GMT > Been thinking, how about something like this: > [snipped; see up-thread] [quoted text clipped - 4 lines] > 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 ...
 Signature Eric.Sosman@sun.com
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|