Java Forum / General / December 2005
a criticism of java
q_q_anonymous@yahoo.co.uk - 08 Dec 2005 00:28 GMT "BufferedReader foo = new BufferedReader(new InputStream(new JavaHatesYou(new FuckOffAndDie(new ForTheLoveOfGodLetMeJustReadTheFile(new File("filename.txt")))))))));"
I think that speaks for itself.
Java may solve some problems that C and C++ had, but that issue demonstrated above is just ridiculous
zero - 08 Dec 2005 00:39 GMT q_q_anonymous@yahoo.co.uk wrote in news:1134001710.533725.51130 @z14g2000cwz.googlegroups.com:
> "BufferedReader foo = new BufferedReader(new InputStream(new > JavaHatesYou(new FuckOffAndDie(new [quoted text clipped - 5 lines] > Java may solve some problems that C and C++ had, but that issue > demonstrated above is just ridiculous BufferedReader foo = new BufferedReader(new FileReader("filename.txt"));
Of course, if you like doing it the long way... ;-)
I do feel that Sun has learned from the same master as Microsoft when it comes to naming classes/methods. FormatFlagsConversionMismatchException anyone?
 Signature Beware the False Authority Syndrome
Chris Smith - 08 Dec 2005 01:57 GMT > BufferedReader foo = new BufferedReader(new FileReader("filename.txt")); I'd actually make that a little longer:
BufferedReader foo = new BufferedReader( new InputStreamReader(new FileInputStream("filename.txt")));
That does exactly the same thing, but the difference is that it's more obvious that the default character encoding is being used... and therefore, that the code should be considered suspect in most situations. It's not possible to use FileReader to read in a specified encoding, and that flaw makes it worth avoiding, if you ask me.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Roedy Green - 08 Dec 2005 02:04 GMT >BufferedReader foo = new BufferedReader(new FileReader("filename.txt")); It takes quite a while to learn how to plug together all the pieces of the java.io lego set. They lack symmetry. In the meantime, you can crank out code using the file I/O amanuensis.
See http://mindprod.com/applets/fileio.html
Properly speaking that is not Java, but one of the Java libraries. If you don't like it you can write your own. Sun itself has written the nio package to try to simplify and speed it up. I think it could easily use another round of orthogonalistation.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Thomas Hawtin - 08 Dec 2005 00:49 GMT > "BufferedReader foo = new BufferedReader(new InputStream(new > JavaHatesYou(new FuckOffAndDie(new [quoted text clipped - 5 lines] > Java may solve some problems that C and C++ had, but that issue > demonstrated above is just ridiculous Yeah, if the FuckOffAndDie constructor really does throw then you will drop the love of god. And you probably don't want to be doing that.
http://jroller.com/page/tackline?entry=factoring_out_exception_handling
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
Noodles Jefferson - 08 Dec 2005 02:59 GMT In article <1134001710.533725.51130@z14g2000cwz.googlegroups.com>, q_q_anonymous@yahoo.co.uk took the hamburger, threw it on the grill, and I said "Oh wow"...
> "BufferedReader foo = new BufferedReader(new InputStream(new > JavaHatesYou(new FuckOffAndDie(new > ForTheLoveOfGodLetMeJustReadTheFile(new > File("filename.txt")))))))));" > > I think that speaks for itself. No, this does:
RandomAccessFile raf = new RandomAccessFile("P:\a\t\h", "rw");
Tadaaaaa.
> Java may solve some problems that C and C++ had, but that issue > demonstrated above is just ridiculous
 Signature Noodles Jefferson mhm31x9 Smeeter#29 WSD#30 sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM
"Our earth is degenerate in these latter days, bribery and corruption are common, children no longer obey their parents and the end of the world is evidently approaching." --Assyrian clay tablet 2800 B.C.
Noodles Jefferson - 08 Dec 2005 03:34 GMT > In article <1134001710.533725.51130@z14g2000cwz.googlegroups.com>, > q_q_anonymous@yahoo.co.uk took the hamburger, threw it on the grill, and [quoted text clipped - 10 lines] > > RandomAccessFile raf = new RandomAccessFile("P:\a\t\h", "rw"); P:\\a\\t\\h
My bad.
> Tadaaaaa. > > > Java may solve some problems that C and C++ had, but that issue > > demonstrated above is just ridiculous
 Signature Noodles Jefferson mhm31x9 Smeeter#29 WSD#30 sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM
"Our earth is degenerate in these latter days, bribery and corruption are common, children no longer obey their parents and the end of the world is evidently approaching." --Assyrian clay tablet 2800 B.C.
Alun Harford - 08 Dec 2005 09:36 GMT > "BufferedReader foo = new BufferedReader(new InputStream(new > JavaHatesYou(new FuckOffAndDie(new > ForTheLoveOfGodLetMeJustReadTheFile(new > File("filename.txt")))))))));" > > I think that speaks for itself. Wait a second... What are you doing with the java.io.IOException?
Alun Harford
q_q_anonymous@yahoo.co.uk - 08 Dec 2005 18:10 GMT > > "BufferedReader foo = new BufferedReader(new InputStream(new > > JavaHatesYou(new FuckOffAndDie(new [quoted text clipped - 7 lines] > > Alun Harford yes, that's another thing in java that would make me mad. Why can't java let you just test if a file exists, if(theFile.exists()) { read it }
I see that writing the whole try catch exception thing allows for the case that the file suddenly disappears after i've done the test. But if that's the case, then let my program crash, and let the user figure it out. That kind of thing is really outside the realm of what a programmer can be reasonably expected to test for! It's not like a programmer should test for a blatant attempt to crash my program ;-) Or for user negligence.
And the alternative to having the whole try catch exception thing is to have a throws. But I don't want that propagating up, for reasons stated above.
Oliver Wong - 08 Dec 2005 20:24 GMT > I see that writing the whole try catch exception thing allows for the > case that the file suddenly disappears after i've done the test. But [quoted text clipped - 3 lines] > It's not like a programmer should test for a blatant attempt to crash > my program ;-) Or for user negligence. Occasionally, you want your program to NOT crash under any conditions. Java gives you this possibility. If you want to allow your program to "just crash" when an FileNotFoundException is thrown, you can do this:
try { /*Code here which may throw FileNotFoundException*/ } catch (FileNotFoundException e) { throw new Error("Gave up.", e); }
> And the alternative to having the whole try catch exception thing is to > have a throws. But I don't want that propagating up, for reasons stated > above. Not nescessarily, as shown above.
- Oliver
q_q_anonymous@yahoo.co.uk - 09 Dec 2005 03:37 GMT > > I see that writing the whole try catch exception thing allows for the > > case that the file suddenly disappears after i've done the test. But [quoted text clipped - 3 lines] > > It's not like a programmer should test for a blatant attempt to crash > > my program ;-) Or for user negligence.
> Occasionally, you want your program to NOT crash under any conditions. > Java gives you this possibility. If you want to allow your program to "just > crash" when an FileNotFoundException is thrown, you can do this: yes, I know how to make a program crash from a FileNotFoundException or how to catch it and throw a different Exception.
My gripe against java, is that I have to write or litter my code with stuff about FileNotFoundException including Try/Catch or Throws.
> try { > /*Code here which may throw FileNotFoundException*/ > } catch (FileNotFoundException e) { > throw new Error("Gave up.", e); > } you are just illustrating my point
> > And the alternative to having the whole try catch exception thing is to > > have a throws. But I don't want that propagating up, for reasons stated > > above. > > Not nescessarily, as shown above. Look what you showed above. It was a "try catch exception thing "
My point is that I test if a file exists, and that's it, i'm done with that. I should then be able to read the file, and not write for FileNotFoundExceptions. It litters the code (relatively) and is relatively time consuming.
In a mythical pascal/java like language it'd be a bit like
procedure foo begin a=assign(abc,'c:\a.txt'); if(abc.exists()==false) {.....[put that right or exit with a descriptive error]......}
while(i++ <n) abc.readLn(); end;
and if, ****during that while loop****, the file suddenly vanishes or becomes unreadable, then let the program crash completely. I don't have to test for that!!!!!
Patrick May - 09 Dec 2005 09:25 GMT > Look what you showed above. It was a "try catch exception thing " > > My point is that I test if a file exists, and that's it, i'm done > with that. I should then be able to read the file, and not write for > FileNotFoundExceptions. It litters the code (relatively) and is > relatively time consuming. You have a valid point, but I don't think the ability to turn off or otherwise completely ignore exceptions is the best solution. In order to improve the legibility of the code and preserve the resiliency provided by exception handling, Java needs a proper macro facility such as that found in Common Lisp. Because of the increasingly complex syntax of Java, such a facility may be impossible to develop.
If you're interested in seeing a proper solution to the problem you have identified, take a look at http://www.gigamonkeys.com/book, chapters 7 and 8 in particular.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML)
q_q_anonymous@yahoo.co.uk - 09 Dec 2005 14:35 GMT > > Look what you showed above. It was a "try catch exception thing " > > [quoted text clipped - 18 lines] > > Patrick Thanks. I'd alway thought that people that criticised exceptions were bludgeoned to death by the java police.
"It's better than testing for error codes" "If you had programmed in C or C++, you'd see that Exceptions are much better than the alternative" "This whole mandatory exception thing, forcing people to check their code, is a really good idea"
Roedy Green - 09 Dec 2005 17:23 GMT >Thanks. I'd alway thought that people that criticised exceptions were >bludgeoned to death by the java police. You get bludgeoned if you troll -- trash something before you understand it.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Dimitri Maziuk - 11 Dec 2005 20:01 GMT q_q_anonymous@yahoo.co.uk sez:
...
> Thanks. I'd alway thought that people that criticised exceptions were > bludgeoned to death by the java police. > > "It's better than testing for error codes" > "If you had programmed in C or C++, you'd see that Exceptions are much > better than the alternative" Well, you've got to agree that a) people don't test for error codes even when they should've, b) there is no "generic error code" from a function that returns a signed int (see also two's complement), c) consolidating all "catch" code into last code pages that will (hopefully) never need to be even swapped in is a Good Thing(tm) performance-wise.
(Speaking of a), they could force people to at least pop function's return value from stack, making it harder to ignore -- and getting overloading on return value as a bonus -- but that'd make it look too much like Pascal. Too scary to contemplate.)
> "This whole mandatory exception thing, forcing people to check their > code, is a really good idea" Declare "myfunc() throws Exception" if you don't want to care.
What ticks me off is that Java's taking it too far in assuming that any error is "exceptional". E.g. (last time I checked) boolean isInt( String s ) { try { Integer.parseInt( s ); return true; } catch( NumberFormatException e ) { return false; } } is orders of magnitude slower than checking if s[0] is a plus, dash, or digit, and s[1..n] are digits -- on input consisting of mostly non-integer strings. Which is fine if non-integer input strings are "exceptionally rare errors" in your problem domain, but IRL you tend to get data with "unk", "n/a", "?", etfc. all the time. (Of course, last I checked none of parseXXX()'s thought 1e2 was a valid number so they were never much use anyway.)
Dima
 Signature "Mirrors and copulation are abominable because they increase the number of entities." -- corollary to Occam's Razor
q_q_anonymous@yahoo.co.uk - 11 Dec 2005 22:54 GMT > q_q_anonymous@yahoo.co.uk sez: > > [quoted text clipped - 8 lines] > Well, you've got to agree that > a) people don't test for error codes even when they should've, but if a programmer is that bad then exceptions won't make him into a good programmer. It might make his program bad rather than aweful. And this is no excuse for making the language horrible. I don't think this was the intention for exceptions anyway, 'cos it'd be a silly reason.
> b) there is no "generic error code" from a function that returns > a signed int (see also two's complement), the fact that a function like parseInt cannot really return an integer when there's an error. You yourself point out the absurdity of using this as an excuse for a (long winded) Exception, since as you say, it's easy to use a boolean function or expression to test for a non integer, and it's not exactly an exception. So, better to test for it with a boolean expression. Then, if parseInt is executed on a non integer, let the program croak. Nothing caught, it's programmer error. Exceptions aren't or catching programmers' errors! It's good for a programmer to test for his own errors, e.g. JUnit, but not catch them, writing recovery code!
> c) consolidating all "catch" code into last code pages that will > (hopefully) never need to be even swapped in is a Good Thing(tm) [quoted text clipped - 9 lines] > > Declare "myfunc() throws Exception" if you don't want to care. That's meant to be bad practice, but, all the sources that say it's bad practice, say so in the context of a person using it because he isn't concerned about the exceptions his methods throw and doesn't understand them. But maybe it's not such a bad idea. If any exceptions go off that I didn't write a try/catch for, then let the program croak, I want it to, because it's a programmer error. Seems good . Strange that 'throws Exception' is so frowned upon! It should go with a comment that says the Exceptions the method can throw. To give some understanding of the code i've done to avoid exceptions being thrown.
> What ticks me off is that Java's taking it too far in assuming > that any error is "exceptional". E.g. (last time I checked) [quoted text clipped - 11 lines] > > Dima YEAH! I absolutely agree with you. Have a boolean expression test if it's an integer. then Run Integer.parseInt on it and if it's not na integer, let the program croak. That goes with the 'throws Exception' philosophy - allowing Exceptions to be thrown like that but retaining presence of mind, knowing waht can be thrown and knowingly letting them - with good reason!
I would still throw an IllegalArgumentException with every method, - not intended to be caught. Including a String describing the mistake. For somebody to call a method without testing the arguments they pass to it, relying on the method they call to test whether their arguments are valid, then getting an IllegalArgumentException from the method telling them what argumetn was invalid, and them catching it, and writing error recovery code, is ridiculous. If they can put error recovery code in a catch - which is rather late - then they can put it early before they call the method!
Hendrik Maryns - 12 Dec 2005 15:04 GMT q_q_anonymous@yahoo.co.uk schreef: <a lot>
> I would still throw an IllegalArgumentException with every method, - > not intended to be caught. Including a String describing the mistake. [quoted text clipped - 5 lines] > recovery code in a catch - which is rather late - then they can put it > early before they call the method! I suppose you aren´t a fan of design on contract either?
H.
 Signature Hendrik Maryns
================== www.lieverleven.be http://aouw.org
q_q_anonymous@yahoo.co.uk - 13 Dec 2005 14:04 GMT > q_q_anonymous@yahoo.co.uk schreef: > <a lot> [quoted text clipped - 9 lines] > > I suppose you aren´t a fan of design on contract either? You mean strictly defining what goes in and out of the method - so the method is designed to fulfill a contract with its user ? Of course I believe in that.
I would test the arguments very carefully and throw IllegalArgumentExceptions if they screw up. I consider them calling my method with illegal arguments to be them screwing up - programmer error.
I'm not sure what text I wrote could have possibly led you to believe what you wrote.
Hendrik Maryns - 13 Dec 2005 14:27 GMT q_q_anonymous@yahoo.co.uk schreef:
>>q_q_anonymous@yahoo.co.uk schreef: >><a lot> [quoted text clipped - 22 lines] > I'm not sure what text I wrote could have possibly led you to believe > what you wrote. Well then you should know that the method signature is a part of the contract, so adding unnecessary throws declarations is just making the contract less attractable. You talk about documenting when which errors can be thrown, why not do part of that in the method signature? This can be formalised, by using the @throws clause, but if you are going to have to describe every possible exception there, you will have more work describing them than writing some more (robust) code which will actually handle the exceptions.
H.
 Signature Hendrik Maryns
================== www.lieverleven.be http://aouw.org
q_q_anonymous@yahoo.co.uk - 13 Dec 2005 17:09 GMT > q_q_anonymous@yahoo.co.uk schreef: > > [quoted text clipped - 27 lines] > Well then you should know that the method signature is a part of the > contract, not the way I am using it. The throws Exception isn't saying this method WILL throw anything. It doesn't actually change what the method throws. It does mean that the code within the method reads a lot better.
in a single user system, a FileNotFoundException while i'm reading a small file is very exceptional. And I won't be dealing with it. Just like I won't be dealing with an Out Of Memory Exception. As far as I'm concerned, it should be unchecked.
So the throws Exception is a orkaround for the problem that i'd like FileNotFoundException and NumberFormatException should be unchecked exceptions. Really, i'd like Integer.parseInt to throw an IllegalArgumentException if I passed it a String. And i'd like FileNotFoundException to be an unchecked, because in my patricular case, I dont' want to recover from it. (I deal with the file not existing before I start reading it, but if it vanishes while reading from it then I personally would let the program crash exit).
If the user really wants to, he can recover from it. But I am the main user of the method, and I can comment that the FileNotFoundException isn't thrown, and I am writing the method for users that don't typically want to recover from it. If they want to it's no problem, they can write their own catch. Just like they can for any other unchecked Exception ilke out of memory exception, or any exception that is outside the programmer's control.
> so adding unnecessary throws declarations is just making the > contract less attractable. The way i'm using the throws, it shouldn't be read as part of the contract. It makes no difference to the existing contract. It says nothing extra. It just says this method could throw an Exception. It makes the code inside the method a lot neater, and the code is just as strong. THe purpose of the throws clause is not for the contract - the way I use it , it says nothing.
>You talk about documenting when which errors > can be thrown, why not do part of that in the method signature? For the same reason that certain exceptions were made Unchecked. The same reason that sun made sure you don't have to write Out of memroy exception in the throws clause.or null pointer exception. These are errors - I think - that are either outside of the programmer's control and thep rogrammer may just want to have the program crash-exit or they are programmer errors.
I am treating the NumberFormatException thrown by parseInt as an IllegalArgumentException, and therefore, something which sun recognizes is an unchecked exception and wouldn't be declared, because if it were thrown, it'd be programmer error. You don't write code to recover from them. You crash-exit
In a typical situation, you woudln't catch these , so I wouldn't declare them and inconveniene the user of the method. If he wants to catch them, he can
>This > can be formalised, by using the @throws clause, but if you are going to > have to describe every possible exception there, you will have more work > describing them than writing some more (robust) code which will actually > handle the exceptions. I'm talking about Exceptions that either shoudl be illegalargumentexceptions or - the way I am using the method - should be unchecked.
sun recognizes exceptions like this. calls them unchecked exceptions.
Hendrik Maryns - 14 Dec 2005 11:44 GMT I think it all boils down to a different point of view, and neither of us will convince the other, so you may read the rest of my reply, or just ignore it. Sorry for the top-post.
q_q_anonymous@yahoo.co.uk schreef:
>>q_q_anonymous@yahoo.co.uk schreef: >> [quoted text clipped - 30 lines] > not the way I am using it. The throws Exception isn't saying this > method WILL throw anything. Indeed, it only warns that the method /could/ throw that particular exception. And if you take DBC seriously, you will mention in the docs under what circumstances that is possible. Thus, the example you gave in another post:
public void methodX() throws Exception { .... if (isInt(string)) int x = parseInt(string); else System.out.println("Not an Int"); }
is rather ridiculous, as now you have to bother the client of the method with reading that you do declare an exception can be thrown, but then you document that actually, it can´t. Why not just put a try/catch around it and not bother the client of your method?
It doesn't actually change what the method
> throws. It does mean that the code within the method reads a lot > better. I think the code within a method is much less important than that what the client gets to see, i.e. the method signature and the documentation.
> in a single user system, a FileNotFoundException while i'm reading a > small file is very exceptional. And I won't be dealing with it. Just > like I won't be dealing with an Out Of Memory Exception. As far as > I'm concerned, it should be unchecked. Ok, but a single user system is not what Java was built for, and for much applications is not the rule, but the exception.
Funny thing is, there are others that claim UNchecked exceptions are a misdesign... (and I tend to agree with them, I always document when a method might throw an NPE or IAE or ...)
> So the throws Exception is a workaround for the problem that i'd like <snip> Indeed, good for a one-person program, which once again is not the rule but the exception.
> If the user really wants to, he can recover from it. But I am the main > user of the method, and I can comment that the FileNotFoundException > isn't thrown, and I am writing the method for users that don't > typically want to recover from it. And you are sure you will never have to hand over your code to another maintainer?
> If they want to it's no problem, they can write their own catch. > Just like they can for any other unchecked Exception ilke out of > memory exception, or any exception that is outside the programmer's > control.
>>so adding unnecessary throws declarations is just making the >>contract less attractable. > > The way i'm using the throws, it shouldn't be read as part of the > contract. But unfortunately, it is.
It makes no difference to the existing contract. It says
> nothing extra. It just says this method could throw an Exception. > It makes the code inside the method a lot neater, and the code is just > as strong. THe purpose of the throws clause is not for the contract - > the way I use it , it says nothing. But how is your client supposed to know that? Probably because you document it, but then that is just as much work, no?
>>You talk about documenting when which errors >>can be thrown, why not do part of that in the method signature? [quoted text clipped - 4 lines] > and thep rogrammer may just want to have the program crash-exit or > they are programmer errors. You have a point, and there would be no need for many of those exceptions if there was a precondition system that checked for null values and the like. (Maybe I really should switch to Eiffel)
> I am treating the NumberFormatException thrown by parseInt as an > IllegalArgumentException, and therefore, something which sun recognizes > is an unchecked exception and wouldn't be declared, because if it were > thrown, it'd be programmer error. You don't write code to recover from > them. You crash-exit Depending on how robust you want your program, even if it is an auxiliary class. Robustness vs. efficiency, the usual dilemma, right?
 Signature Hendrik Maryns
================== www.lieverleven.be http://aouw.org
q_q_anonymous@yahoo.co.uk - 14 Dec 2005 16:41 GMT > I think it all boils down to a different point of view, and neither of > us will convince the other, so you may read the rest of my reply, or > just ignore it. Sorry for the top-post. The throws clause is part of the language and not an effective tool for documenting the method. If you use it as such, then you have to deal with the fact that it doesn't demand listing 'unchecked exceptions'*, and doesn't list preconditions and postconditions. Documentation should be in English rather than java code that wasn't intended for that!
(* I personally wouldn't document all kinds of unchecked exceptions. Cerainly not programmer errors. Maybe some related to outside environment though. )
Not having checked exceptions declared in those instances as I suggested, will not make the program less robust. If they are declared, as you would. Or if they are not declared as I would, it still means that we're not dealing with it.
In the rare event that the user will deal with an unchecked exception (and they are rare hence the exception is unchecked). In that rare event, the user may catch the exception, he has the choice to do so, but he is not forced to catch or declare it. To force the programmer to do so, is a self imposed restriction that comes at too great a cost. It's absurd to list all the unchecked exceptions in the throws clause, as you suggest. Especially programmer errors within the method, like NullPointerException. Do you think the user of the method is going to see that and think "arr, I forgot that might be throw, I might want to catch it". The user of the method should be aware that exception may be thrown. Checked exceptions come at a great cost.
A programmer that isn't absolutely aweful, can write robust code with just unchecked exceptions. He doesn't have to be forced to catch one or to declare every unforeseen possibility in java code. possibilities which will rarely be dealt with, but can be dealt with even without him listing them in java code. His only excuse is he is abusing it as a documentation tool, that is crazy. It's java code!
How about writing good code, and good documentation ! And not try to include documentation in a throws clause, cluttering the method header, cluttering the method body. And, as I said. Documentation shouldn't be in java code. so, i'm not saying it shouldn't be in non english. Efforts are being made in academic circles to use mathematical symbols to document programs. e.g. to say that an array is sorted. But the point is that java code isn't flexible enough to do this. It wasn't built for documenting programs.
I am all for descriptive documentation, and that does take longer to write.
I also put an IAE in the throws clause. Because I manually throw an IAE with a descriptive String. It's not an unchecked exception that just gets thrown due to my error or the outside environment. It's user error, and I want him to know he can't get away with it! But this is no replacement for proper documentation. I would never let my throws clause document my program at the cost of my code Or at the cost of causing unnecessary frustration to the user of the method!!
> q_q_anonymous@yahoo.co.uk schreef: > > [quoted text clipped - 134 lines] > www.lieverleven.be > http://aouw.org ricky.clarkson@gmail.com - 14 Dec 2005 19:16 GMT > The throws clause is part of the language and not an effective tool for > documenting the method. Am I to take this to mean that documentation needs to duplicate the source code?
/** @param values an array of type int passed in using the varargs syntax. @return an int which is one of the passed in values. */ int giveOneBackAtRandom(int... values) { return values[(int)(Math.random()*values.length)]; }
It seems to me that the 'int' nature of the parameters and return type is better expressed in the language. Now suppose I change this method to use doubles:
/** @param values an array of type int passed in using the varargs syntax. @return an int which is one of the passed in values. */ double giveOneBackAtRandom(double... values) { return values[(int)(Math.random()*values.length)]; }
I've got a mismatch between comment and code, caused by the comment duplicating the code. Here is a better comment:
/** @return one of the parameters, chosen at random. */
Much more concise, and as it happens, it's more useful too, because earlier I was concentrating on filling in @param and @return, getting the return type right, etc., and completely forgot to mention randomness.
> Efforts are being made in academic circles to use mathematical symbols > to document programs. e.g. to say that an array is sorted. Why not use a SortedSet, or a custom implementation that wraps an array or always making sure it is sorted? Then it will be blindingly obvious that it's sorted, because it will be of type SortedArray or something.
The code should be as expressive as is practical, to enforce contracts. That's the great advantage of static typing, we can have contracts. In dynamically-typed languages, we can do stuff like:
/* Adds the specified item to the specified list */ function push(var list,var item) { list.add(item); }
Then someone comes along and types the parameters in the wrong order, and ends up adding a list to a string instead of a string to a list. The runtime doesn't notice. This is because the contract is not expressed in code, it is expressed in documentation. Documentation isn't as strict as a static-type-checking language:
public static <T> void push(final List<T> list,final T item) { list.add(item); }
This not only catches the above bug, but prevents some other bugs, like adding a Banana to a List<String>, for example. A real case I've seen recently is a new programmer mixing up Strings and JTextFields, and unfortunately using 1.4.
So if you need to specify part of the contract in documentation, you're probably fighting the language or lamenting something you wish it had.
q_q_anonymous@yahoo.co.uk - 14 Dec 2005 23:00 GMT > > The throws clause is part of the language and not an effective tool for > > documenting the method. > > Am I to take this to mean that documentation needs to duplicate the > source code? That wasn't what I meant, but what the advice you wrote is lucid and wise.
Personally, I tend to write reams of notes for a method , and write it outside the code, because it'd just make the code unreadable. I wouldn't call it documentation since it's more notes to self, and I wouldn't expect anybody else to read it until I tidy it up. It's more whitebox notes.
I do write brief 'whitebox' notes in the code within the method too
But yes. Blackbox notes, just what goes in and out of the method, that can be included in the code , and is a commentary on the method header.
I'm glad you posted this, because, although I wasn't disagreeing with it, it has clarified things for me.
Blackbox documentation, is a commentary on the method header. Thus, you are wise in - it seems to me - saying that the blackbox documentation shouldn't duplicate what is written in the method header. Like variable types. And that strict typing helps document the code too, (as well as preventing errors)
I was really only referring to after the throws clause. But I wasn't even being that radical. No doubt that what is after the throws clause is useful for documenting the method, but it shouldn't be adapted to provide documentation for the method. I was debating with a guy that appeared to me to not agree with unchecked exceptions, so he thought that all exceptions should be checked, and thus would have no qualms in listing all exceptions, including 'out of memory' exception and others, on the end of a throws clause. Declaring checked exceptions has ramifications. It's not necessarily that I disagree with all checked exceptions. But those examples I gave are from my short experiences with java, and those method shouldn't have been throwing checked exceptions.
> /** > @param values an array of type int passed in using the varargs [quoted text clipped - 31 lines] > the return type right, etc., and completely forgot to mention > randomness. you speak wisely
> > Efforts are being made in academic circles to use mathematical symbols > > to document programs. e.g. to say that an array is sorted. > > Why not use a SortedSet, or a custom implementation that wraps an array > or always making sure it is sorted? Then it will be blindingly obvious > that it's sorted, because it will be of type SortedArray or something. That'd probably be better given the goal of sorting the array using the java language.
But that'd just be as a demonstration for what can be done. I'm not an academic, but i'm aware that there is work by Professor Bornat to prove the correctness of programs using Hoare Logic. So no doubt it gets mroe sophisticated than proving the correctness of a method to sort an array.
> The code should be as expressive as is practical, to enforce contracts. > That's the great advantage of static typing, we can have contracts. [quoted text clipped - 13 lines] > expressed in code, it is expressed in documentation. Documentation > isn't as strict as a static-type-checking language: indeed. I wouldn't make documentation a substitute for code or code a substitute for documentation. But sometimes they complement one another as you demonstrate. And the method header forms part of the documentation, or the subject, of the documentation's commentary.
> public static <T> void push(final List<T> list,final T item) > { [quoted text clipped - 8 lines] > So if you need to specify part of the contract in documentation, you're > probably fighting the language or lamenting something you wish it had. Perhaps documentation within the code shouldn't duplicate what is in the method header. But I think that the chap I was discussing/debating with was lamenting that unchecked exceptions weren't actually checked, and he might have wanted to declare all of those.
I would say that they certainily shouldn't be written in the method header. (java has unchecked exceptions - I believe with good reason).
He may write them in his documentation (though I wouldn't do that in the 'in code' blackbox documentation - it wouldn't be brief enough to be there). It'd be in the exhaustive whitebox documentation that is mostly my thoughts gathered together in a structured manner as I program.
And, my beef was with certain methods throwing checked exceptions when I felt they should've been throwing unchecked exceptions. Thus, I didn't want to be declaring them after the throws. If I were to document that they are thrown, I'd write outside the source file, and certainly not write them in the code. There are so many unchecked exceptions. I would not adapt the throws clause to provide documentation to a checked exceptions that should really be unchecked.
Hence In those instances, I support not declaring them, by saying.
public int methodQ(String a) throws Exception { }
I would also manually throw the unchecked IllegalArgumentException, and I might declare that, since I think that exception is very relevant as a reminder to the programmer.
By the way. I see your understanding is lucid. Are you a teacher? Do you recommend any particular book or sources of info for improving my programming?
Where I see wisdom, I take advice. I see wisdom!
ricky.clarkson@gmail.com - 17 Dec 2005 16:37 GMT > And, my beef was with certain methods throwing checked exceptions when > I felt they should've been throwing unchecked exceptions. What do you base this feeling on?
Anyway, if you do think that the method should throw an unchecked exception, wrap it.
public static void sleep(final int milliseconds) { try { Thread.sleep(milliseconds); } catch (final InterruptedException exception) { throw new RuntimeException(exception); } }
I personally don't ever specify unchecked exceptions in throw clauses, because that's code that has no effect.
> I would not adapt the throws clause to provide documentation to a > checked exceptions that should really be unchecked.
> Hence In those instances, I support not declaring them, by saying.
> public int methodQ(String a) throws Exception > { > > } No, you are adapting the throws clause. If you say that you throw Exception, then you are forcing the callers of your method to do the same, or catch Exception. This is pointless.
Unless you actually do throw instances of Exception, not subclasses, which itself would be pointless, you should declare to throw all checked exceptions. If you don't want checked exceptions in your signatures at all, then Exception is no better. Here's my usual solution (really the previous one repeated):
public void doSomething() { try { code } catch (final IOException exception) { throw new RuntimeException(exception); } catch (final SQLException exception) { throw new RuntimeException(exception); } }
If you force people to catch Exception, you are forcing them to catch RuntimeException too, which is usually not desired. I would ALWAYS have separate catch blocks for each checked exception type, and a separate one for RuntimeException. CheckStyle and findbugs have a little to say on the matter, and can point out this error in your code:
http://findbugs.sourceforge.net/bugDescriptions.html#REC_CATCH_EXCEPTION http://checkstyle.sourceforge.net/config_coding.html#IllegalCatch
> I see your understanding is lucid. Are you a teacher? Partly. I am a Research Assistant at the University of Salford, where I work on Netsim ( www.netsim.info ) and tutor on a couple of modules. I also lecture some A-Level students from a local college. My rushed notes used for beginners in Java are available:
http://cime.net/~ricky/netsim/oldham/index.html
Primarily, I'm a programmer, so I learn from my own experience.
> Do you recommend any particular book or sources of info for improving > my programming? I found the idea of not duplicating code in comments in Bjarne Stroustrup's C++ book, some years ago.
I just discuss ideas with other developers really, normally via IRC (Freenode).
q_q_anonymous@yahoo.co.uk - 17 Dec 2005 18:32 GMT > > And, my beef was with certain methods throwing checked exceptions when > > I felt they should've been throwing unchecked exceptions. > > What do you base this feeling on? by the way. thanks for the corrections which you made to many of the things I suggested in the previous post.
a)Integer.parseInt was one of the method that got up my nose. It throws a NumberFormatException - which is, checked.
b) BufferedReader br = new ..........FileReader(....) that'll throw a FileNotFoundException (which is checked) and c) - related to b br.read(...) <-- that'll throw an IOException (which si checked)
In the case of 'a' - integer.parseInt throwing the checked exception
Regarding the Integer.parseInt example. A method that returns a boolean, could discern whether it is an integer. Then one could call a method like Integer.parseInt which would throw an IllegalArgumentException if it was passed a String that wasn't representing an Integer .
String tbox="12345" if(testint(tbox)) Integer.parseInt(tbox); else System.out.println("Enter an integer");
Regarding FileReader throwing a FileNotFoundException. Again, I can test if the file exists, and so, if I were to call FileReader, passing it a file that didn't exist, then I would want an IllegalArgumentException thrown. It's an error I could avoid and I wouldn't write code to recover from it since it'd be programmer error. Fine, in a multiuser application - many threads, some user may delete the file after I verify that it exists. But since i'm writing a single user / single thread, application, that sort of mischief isn't expected, and I rightly don't want to check and recover from that. Let thep program crash if the moment after I test for the file's existance, the file disappears!. If it were an unchecked exception, i'd have the choice to catch it if I wanted to deal with it. But here - it beign a checked exception - I am forced to catch it or declare it in the throws
Regardign c - br.read(..) . that I can understand, if it's a big file, maybe the file will disappear. But still, I shouldn't be forced to recover from that. Suppose I'm reading a small file, it'll take less than 5 seconds to read. If the file suddenly disappears, then it's blatant user negligence, and I don't want to code for that possibility, I'm happy for the program to crash.
I think, your solution may be the only one. To catch the specific checked Exceptions and throw a Runtime Exception (which is unchecked). It's still longwinded though. And those methods I mention are quite common.
I guess that since they are common, one could rewrite versions of those methods that don't throw checked exceptions.
> Anyway, if you do think that the method should throw an unchecked > exception, wrap it. [quoted text clipped - 27 lines] > Exception, then you are forcing the callers of your method to do the > same, or catch Exception. This is pointless. yeah, it was silly. That all encompassing Exception was of course a Checked Exception.
> Unless you actually do throw instances of Exception, not subclasses, > which itself would be pointless, you should declare to throw all [quoted text clipped - 26 lines] > http://findbugs.sourceforge.net/bugDescriptions.html#REC_CATCH_EXCEPTION > http://checkstyle.sourceforge.net/config_coding.html#IllegalCatch yikes, so, I won't be doing that catch exception adn throws exception!
How about this, which rethrows unchecked exceptions like NPEs and IAE
try {
/* code with Integr.parseInt, FileReader, .read(..) */
} catch(Exception e) { /* Have a method that tests the Exception, if it is an IOException or a FileNotFoundException, then the method will catch it - swallowing it. Otherwise, it's some other exception, like a unchecked IAE or NPE. So it'll throw that Exception back out. */
}
ricky.clarkson@gmail.com - 18 Dec 2005 21:35 GMT > a)Integer.parseInt was one of the method that got up my nose. It > throws a NumberFormatException - which is, checked. The problem with the test-first strategy is that you are duplicating effort. Nearly all the effort required to parse an int is required to verify an int.
See the recent thread on "Using exceptions for early exit" in comp.lang.java.programmer for my suggestions (and some counter-arguments) on alternative ways of doing this.
> But since i'm writing a single > user / single thread, application, that sort of mischief isn't > expected I would never trust a user (even/especially myself) not to delete a file under my nose. If you can trust a user, then you are dealing with a VERY VERY rare case. Most users do mischevious things if they can.
By the way, FileReader is worth avoiding because you can't set its encoding. It uses the default platform encoding (unless you change that). It's better to use InputStreamReader, I think.
> Regardign c - br.read(..) . that I can understand, if it's a big > file, maybe the file will disappear. I don't think a file can be deleted if you're reading from it, but that might be OS-dependent. However, a filesystem might disappear, especially a remote one.
Also, you might close the FileReader before the BufferedReader, so the BufferedReader has to throw an IOException in that case.
The problem with using this construct:
try { code } catch (final Exception exception) { if (exception instanceof RuntimeException) throw (RuntimeException(exception;
logger.log(exception); }
is that it is not explicit. You might think that you're handling an IOException and a NumberFormatException with it, then you might add some code that does an SQL query. It will silently start catching SQLException, and just logging it. It would be better to have to deal with SQLException, so that you can, e.g., close the database Connection and System.exit(1); or whatever you want to do in the case of an SQLException.
Being explicit is good for avoiding bugs, but not good for stopping you from having to type a lot. I don't mind typing a lot (if you haven't noticed). I do mind hunting bugs.
Dimitri Maziuk - 15 Dec 2005 07:43 GMT Hendrik Maryns sez: ...
> Ok, but a single user system is not what Java was built for, and for > much applications is not the rule, but the exception. [quoted text clipped - 7 lines] > Indeed, good for a one-person program, which once again is not the rule > but the exception. Says who? I think if you examine your desktop computer closely, you'll find that > 50% of applications there are inherently single-user.
There's a whole lot of applications that are (or should be) fault-oblivious: if something bad happens, they should just crash. Because trying to recover gracefully and correctly is not worth the trouble, if at all possible. Java gets quite annoying if you're writing an application like that.
Dima
 Signature True courage comes from steadying yourself and forcing yourself to ssh into the fscking thing yet again and not admitting that it doesn't care what it's done to your life. -- "Hidden among the nodes" by ADB
EricF - 16 Dec 2005 04:43 GMT >Hendrik Maryns sez: >.... [quoted text clipped - 14 lines] >you'll find that > 50% of applications there are inherently >single-user. How many of them are written in Java?
>There's a whole lot of applications that are (or should be) >fault-oblivious: if something bad happens, they should just >crash. Because trying to recover gracefully and correctly is >not worth the trouble, if at all possible. Java gets quite >annoying if you're writing an application like that. Than use another language. If I recall correctly, 1 of the design goals of Java was to make the language robust. It forces you to consider errors, unlike C or C++. I agree that exception handling can be annoying, but it keeps me out of trouble if I use it correctly.
Eric
Dimitri Maziuk - 16 Dec 2005 17:18 GMT EricF sez:
... I think if you examine your desktop computer closely,
>>you'll find that > 50% of applications there are inherently >>single-user. > > How many of them are written in Java? I hear Sun has an entire desktop environment written in it.
...
>>fault-oblivious ...
> Than use another language. If I recall correctly, 1 of the design goals of > Java was to make the language robust. It forces you to consider errors, unlike > C or C++. I agree that exception handling can be annoying, but it keeps me out > of trouble if I use it correctly. Exceptions are a Good Thing(tm). Making exception part of method signature -- not so much. You have to jump through hoops if you want to just let it crash, you have to jump through hoops if you want to overload on exception (e.g. read() method that throws SQLException when backed by a DB, IOException when backed by flat file, and no exception when backed by in-memory storage), etc.
Dima
 Signature ...the mainstream products of major vendors largely ignore these demonstrated technologies... [Instead, their customers] are left with several ineffective solutions collected under marketing titles like "defense in depth". -- Thirty Years Later: Lessons from the Multics Security Evaluation
EricF - 17 Dec 2005 06:23 GMT >EricF sez: >> In article <slrndq27ka.jms.dima@yellowtail.bmrb.wisc.edu>, "dmaziuk at bmrb [quoted text clipped - 7 lines] > >I hear Sun has an entire desktop environment written in it. Actually that's not true - but since they call it the Java Desktop System, it's an easy mistake to make.
http://www.sun.com/software/javadesktopsystem/index.xml
I saw Gosling give a demo of it when it was running on Linux. It was pretty cool. Now it runs on Solaris. I think it just a windowing system with some bundled applications, some which very well may be written in Java.
>.... >>>fault-oblivious [quoted text clipped - 14 lines] > >Dima If you don't want to deal with it - and that's legit - than catch it and throw a runtime exception. It doesn't have to be part of the method signature.
try { .. } catch (Exception e) { throw new RunTimeException(e); }
Eric
Oliver Wong - 12 Dec 2005 18:44 GMT [snip]
>> b) there is no "generic error code" from a function that returns >> a signed int (see also two's complement), [quoted text clipped - 8 lines] > it's programmer error. Exceptions aren't or catching programmers' > errors! You're saying writing code like this is stupid:
<stupidCode> if (isInt(string)) { try { int x = parseInt(string); } catch(NumberFormatException e) { System.out.println("Oops, I guess this isn't an int after all."); } } else { System.out.println("Not an int!"); } </stupidCode>
and you're right! It is stupid. Instead, you should write code like this:
<betterCode> try { int x = parseInt(string); } catch(NumberFormatException e) { System.out.println("Not an int!"); } </betterCode>
> Have a boolean expression test if it's an integer. > then Run Integer.parseInt on it and if it's not na integer, let the > program croak. That goes with the 'throws Exception' philosophy - > allowing Exceptions to be thrown like that but retaining presence of > mind, knowing waht can be thrown and knowingly letting them - with good > reason! That's akin to this:
<code> if (isInt(string)) { try { int x = parseInt(string); } catch(NumberFormatException e) { /* string must be parseable because we checked it just a few moments ago. */ throw new Error("This should never happen."); } } else { System.out.println("Not an int!"); } </code>
> I would still throw an IllegalArgumentException with every method, - > not intended to be caught. Including a String describing the mistake. [quoted text clipped - 5 lines] > recovery code in a catch - which is rather late - then they can put it > early before they call the method! IllegalArgumentException is an unchecked exception, and unchecked exceptions are NOT meant to be caught. You are SUPPOSED to let the program "just croak". In other words, Java is already designed with this in mind.
- Oliver
q_q_anonymous@yahoo.co.uk - 13 Dec 2005 16:44 GMT > [snip] > [quoted text clipped - 34 lines] > } > </betterCode> I'm glad you gave a code example, it clarifies. That wasn't what I meant. I"ll show you the code I meant.
I'd rather Integer.parseInt threw an IllegalArgumentException, but since it throws a checked Exception, i'll add a throws Exception to the method header. I won't add a thows numberFormatException to the header because if that is thrown, it's my programming error for passing what i'd consider an IllegalArgument to parseInt. I wouldn't expect somebody else to catch it.
This is what I meant
public void methodX() throws Exception { .... if (isInt(string)) int x = parseInt(string); else System.out.println("Not an Int"); }
I notice I have beef with NumberFormatException thrown bY parseInt - which I would try to ensure isn't thrown and would never catch (if it wre thrown it'd be my programming error).
I have some beef with FileNotFoundException thrown by readLn (which I don't always want to catch). So, I think that's fine being thrown, but it should be unchecked. So maybe it's Checked Exceptions I have beef with, because sometimes they should be IllegalArgumentExceptions , and sometimes, I don't want to catch them - I wnat the program to crash-exit.
> > Have a boolean expression test if it's an integer. > > then Run Integer.parseInt on it and if it's not na integer, let the [quoted text clipped - 19 lines] > } > </code> Interesting interpretation! But No.
The code I wrote in this post illustrates. When I said 'throws Exception philosophy' i was talking about putting that in the method header, for reasoons written above - in this post. The only Exception I speak of manually throwing is the (unchecked) IllegalArgumentException.
> > I would still throw an IllegalArgumentException with every method, - > > not intended to be caught. Including a String describing the mistake. [quoted text clipped - 9 lines] > exceptions are NOT meant to be caught. You are SUPPOSED to let the program > "just croak". In other words, Java is already designed with this in mind. Yes, thanks, that makes good sense.
I guess my isuee is with Checked Exceptions.
Dimitri Maziuk - 13 Dec 2005 17:20 GMT q_q_anonymous@yahoo.co.uk sez: ...
> I notice I have beef with NumberFormatException thrown bY parseInt - > which I would try to ensure isn't thrown and would never catch (if it [quoted text clipped - 6 lines] > they should be IllegalArgumentExceptions , and sometimes, I don't want > to catch them - I wnat the program to crash-exit. Well, with exists( file ) all you get from "test-then-(open-or-throw)" vs. "open-or-throw" is an extra test that doesn't guarantee anything anyway, so you might as well skip it.
Also e.g. if( exists( file ) ) open( file ) // -- OK if program crashes here
But do tempname = generate_random_name() while( exists( tempname ) ) open( tempname ) // -- does not crash ...
In this case 2 processes may well write to a single temp. file. They crash much later when they try to read the file back in, and that's not what you want.
Dima
 Signature Backwards compatibility is either a pun or an oxymoron. -- PGN
Oliver Wong - 13 Dec 2005 21:43 GMT [snip]
> I guess my isuee is with Checked Exceptions. Okay, I had earlier thought you wanted to "ban all exceptions" or something. Anyway, if that's your main beef with Java, you might like C#. They're relatively similar, but ALL exceptions in C# are unchecked.
- Oliver
q_q_anonymous@yahoo.co.uk - 15 Dec 2005 17:35 GMT > [snip] > > [quoted text clipped - 5 lines] > > - Oliver Thank you, you have tempted me to check out C#. Originally I just knew that exceptions bugged me, but thanks to your line of inquiry, I have a more thorough understanding. I hope this thread is useful for others that also became frustrated with Exceptions for the same reasons. Your inquiry and code examples, really pinpointed the issue. The other issue that they are long winded was neatly addressed by the poster that mentioned the macro language. But, as you helped discern, my problem was largely with certain methods throwing checked exceptions. or checked exceptions generally. I now have a more sophisticated understanding of java's language design, and C#'s.
EricF - 10 Dec 2005 06:59 GMT >> Look what you showed above. It was a "try catch exception thing " >> [quoted text clipped - 18 lines] > >Patrick I missed the original post but I disagree with the point that if the file exists, you don't need to worry about a FileNotFoundException. Many of us work in multiuser environments. The file could be deleted right after you check for its existence. Is this likely? Probably not. But in some environments it could happen.
I agree that exception handling code can be a pain but turning it off or ignoring it is not what you want to do. You have the option of letting the exception propagate to the caller by letting the method throw the exception if you don't want to deal with it.
It would be great if Java had macro capabilities like Lisp and I will look at the link. I haven't touched CL since grad school but it was very cool. There are only 2 things I dislike about Lisp. The parentheses are a pain (I got used to them) and it's not very marketable.
Eric
Patrick May - 10 Dec 2005 11:07 GMT > I missed the original post but I disagree with the point that if the > file exists, you don't need to worry about a > FileNotFoundException. Many of us work in multiuser > environments. The file could be deleted right after you check for > its existence. Is this likely? Probably not. But in some > environments it could happen. For the record, I agree with you. The original poster suggested eliminating those exceptions, which would indeed significantly impact the resiliency of the system.
My point was that a decent macro capability would allow the programmer to increase legibility without reducing resiliency.
> It would be great if Java had macro capabilities like Lisp and I > will look at the link. I haven't touched CL since grad school but it > was very cool. There are only 2 things I dislike about Lisp. The > parentheses are a pain (I got used to them) Parentheses in Lisp are like anti-Fnords. When you no longer notice them, you have reached enlightenment.
> and it's not very marketable. But what it enables is _very_ marketable.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML)
Oliver Wong - 09 Dec 2005 15:46 GMT > My point is that I test if a file exists, and that's it, i'm done with > that. I should then be able to read the file, and not write for [quoted text clipped - 16 lines] > becomes unreadable, then let the program crash completely. I don't have > to test for that!!!!! The point I was getting at is that by having these exceptions, you have a choice of either doing something with it, or just letting it crash. If there were no exceptions (i.e. the program just silently fails) then you would have no choice.
- Oliver
Danno - 08 Dec 2005 23:01 GMT > yes, that's another thing in java that would make me mad. > Why can't java let you just test if a file exists, if(theFile.exists()) > { read it } http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#exists()
q_q_anonymous@yahoo.co.uk - 09 Dec 2005 03:20 GMT > > yes, that's another thing in java that would make me mad. > > Why can't java let you just test if a file exists, if(theFile.exists()) > > { read it } > > http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#exists() err, ok, so that tests that the file exists. Part 2 - read the file. I know it exists, and java wants me to type out a try/catch or throws with FileNotFoundExceptions looks relatively time consuming and messy.
Roedy Green - 09 Dec 2005 05:06 GMT >err, ok, so that tests that the file exists. Part 2 - read the file. I >know it exists, and java wants me to type out a try/catch or throws >with FileNotFoundExceptions looks relatively time consuming and messy. The problem is, in a multiuser system some other job could delete the file between the time you test and open.
You can just open and catch the exception. You don't need a separate test.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Dag Sunde - 10 Dec 2005 13:03 GMT >> > "BufferedReader foo = new BufferedReader(new InputStream(new >> > JavaHatesYou(new FuckOffAndDie(new [quoted text clipped - 11 lines] > Why can't java let you just test if a file exists, if(theFile.exists()) > { read it } Eh...?
boolean exists = (new File("Filename")).exists();
 Signature Dag.
Thomas Weidenfeller - 08 Dec 2005 09:45 GMT > "BufferedReader foo = new BufferedReader(new InputStream(new > JavaHatesYou(new FuckOffAndDie(new [quoted text clipped - 5 lines] > Java may solve some problems that C and C++ had, but that issue > demonstrated above is just ridiculous We have comp.lang.java.advocacy. Please use it. fup set.
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
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 ...
|
|
|