Java Forum / General / July 2007
Why no "cause" constructors for NumberFormatException
dvdavins@pobox.com - 10 Jul 2007 06:10 GMT IllegalArgumentException implements the (relatively) new contructors that include a Trhowable as a "cause". But NumberFormatException, which extends IllegalArgumentException, does not. Anybody know why?
Roedy Green - 10 Jul 2007 08:07 GMT >IllegalArgumentException implements the (relatively) new contructors >that include a Trhowable as a "cause". But NumberFormatException, >which extends IllegalArgumentException, does not. Anybody know why? See file://localhost/E:/program%20files/Java/jdk1.6.0_01/docs/api/java/lang/NumberFormatException.html#NumberFormatException(java.lang.String)
You can pass a "cause" string. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Lew - 10 Jul 2007 12:32 GMT >> IllegalArgumentException implements the (relatively) new contructors >> that include a Trhowable as a "cause". But NumberFormatException, >> which extends IllegalArgumentException, does not. Anybody know why? > > See <http://java.sun.com/javase/6/docs/api/java/lang/NumberFormatException.html#Numbe rFormatException(java.lang.String)>
> You can pass a "cause" string. You can also call initCause(), can't you?
 Signature Lew
Twisted - 10 Jul 2007 08:08 GMT On Jul 10, 1:10 am, dvdav...@pobox.com wrote:
> IllegalArgumentException implements the (relatively) new contructors > that include a Trhowable as a "cause". But NumberFormatException, > which extends IllegalArgumentException, does not. Anybody know why? I guess they forgot it, or just haven't gotten around to it yet. Submit it to Sun's bug tracker and they'll probably have it in Java 7.
Patricia Shanahan - 10 Jul 2007 13:24 GMT > On Jul 10, 1:10 am, dvdav...@pobox.com wrote: >> IllegalArgumentException implements the (relatively) new contructors [quoted text clipped - 3 lines] > I guess they forgot it, or just haven't gotten around to it yet. > Submit it to Sun's bug tracker and they'll probably have it in Java 7. I'm not so sure of that. Does a Throwable cause really make sense, given the definition of NumberFormatException?
Patricia
dvdavins@pobox.com - 10 Jul 2007 14:16 GMT > I'm not so sure of that. Does a Throwable cause really make sense, given > the definition of NumberFormatException? Yes. For instance, since you can't set the message, the only way to effectively do so is to catch the oroginal NumberFormatException and to throw a new one with the message that's needed. It would be good to then include the original as the cause. (Better, IMO, would be to be able to set the message directly, but that's a broader issue with Throwable.)
Lew - 10 Jul 2007 16:03 GMT >> I'm not so sure of that. Does a Throwable cause really make sense, given >> the definition of NumberFormatException? [quoted text clipped - 5 lines] > able to set the message directly, but that's a broader issue with > Throwable.) Didn't the suggestion to use initCause() help?
Lew wrote:
> You can also call initCause(), can't you? <http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html#initCause(java.la ng.Throwable)>
 Signature Lew
Lew - 10 Jul 2007 16:14 GMT >>> I'm not so sure of that. Does a Throwable cause really make sense, given >>> the definition of NumberFormatException? [quoted text clipped - 5 lines] >> able to set the message directly, but that's a broader issue with >> Throwable.) This all begs the questions of why you're rethrowing the exception (or one based on it) instead of logging and handling it, and why you need a different message if you haven't handled the Exception, and why you have to throw NumberFormatException instead of a custom application-specific (possibly checked) Exception since you aren't handling it at first catch, and why you are accepting possibly invalid number formats for conversion instead of prevalidating them in the first place, for all of which we will stipulate that you have good reasons for bucking the best-practices trend. For others reading this thread, these questions might be relevant.
 Signature Lew
dvdavins@pobox.com - 10 Jul 2007 16:33 GMT > This all begs the questions of why you're rethrowing the exception (or one > based on it) instead of logging and handling it, and why you need a different [quoted text clipped - 5 lines] > you have good reasons for bucking the best-practices trend. For others > reading this thread, these questions might be relevant. The exception is being thrwon as a direct resulot of bad user input, that so far is coming from a command line. If this program evloves so that it's ever used by more than my friends, I'll have other ways to enter what anmunt to environment variables. In the mean time, I want to give the users meaningful feedback in the console.
Patricia Shanahan - 10 Jul 2007 17:08 GMT >> This all begs the questions of why you're rethrowing the exception (or one >> based on it) instead of logging and handling it, and why you need a different [quoted text clipped - 11 lines] > enter what anmunt to environment variables. In the mean time, I want > to give the users meaningful feedback in the console. I've had similar situations, but the new exception was derived from a special ValidationException that I used if, and only if, the exception was caused by bad user input. That affected how the exception was reported at the user interface layer.
Patricia
dvdavins@pobox.com - 10 Jul 2007 16:33 GMT > Didn't the suggestion to use initCause() help? Yes, that's what I'm doing. It's just odd, IMO, that it's necessary.
Roedy Green - 10 Jul 2007 22:19 GMT >Yes. For instance, since you can't set the message, but you CAN. See
http://java.sun.com/javase/6/docs/api/java/lang/NumberFormatException.html#Numbe rFormatException(java.lang.String) -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Twisted - 11 Jul 2007 00:05 GMT On Jul 10, 5:19 pm, Roedy Green <see_webs...@mindprod.com.invalid> wrote:
> On Tue, 10 Jul 2007 06:16:21 -0700, dvdav...@pobox.com wrote, quoted > or indirectly quoted someone who said : [quoted text clipped - 4 lines] > > http://java.sun.com/javase/6/docs/api/java/lang/NumberFormatException...) You can if you write "throw new NumberFormatException(...)" into your code. This is exactly what the OP is doing; they got a NumberFormatException tossed up from code that isn't theirs (or even from the VM, though I think that's unlikely with this particular exception, unlike say ArithmeticException) and want their own code to then emit a NumberFormatException with the detail message of their choice. The only way to do that is to throw a new one, and the best practise when throwing a new exception because of an old exception is to wrap the old exception as the "cause" of the new one... Of course, if they'd only included an "initDescription" as well as "initCause" in Throwable, he could just change the detail message of the preexisting exception and rethrow it...
Twisted - 10 Jul 2007 20:37 GMT > > On Jul 10, 1:10 am, dvdav...@pobox.com wrote: > >> IllegalArgumentException implements the (relatively) new contructors [quoted text clipped - 6 lines] > I'm not so sure of that. Does a Throwable cause really make sense, given > the definition of NumberFormatException? Is it our place as programmers to question the users when they say they desire a feature? Or just to implement it?
In any event, the OP explained elsewhere that they wanted to wrap some RuntimeExceptions whose construction isn't under their control with copies that add a detail message. I suppose they *could* wrap them in a different exception type, but really, should they be *forced* to? The fact that they can use "initCause" suggests the answer to that is no, since they aren't in fact forced to. Instead they just have to jump through extra hoops to throw the exception they want to throw, which appears to benefit nobody.
Patricia Shanahan - 10 Jul 2007 21:15 GMT ...
> Is it our place as programmers to question the users when they say > they desire a feature? Or just to implement it? ...
I'm a student, so it is definitely my place to question things. However, I've been asking questions about computer programming for 40 years, and see no reason to stop now.
Implementing every requested feature, without questioning the tradeoffs involved, would be an absolute disaster for future maintainability of any computer program or programming language.
Patricia
Twisted - 11 Jul 2007 00:00 GMT > Implementing every requested feature, without questioning the tradeoffs > involved, would be an absolute disaster for future maintainability of > any computer program or programming language. One could argue that it's the user's own darn fault for requesting so many features if the system then becomes a feeping creature. :)
More significantly, in this specific case we're talking about adding one constructor to one library class, hardly a major change or complication of the language. In fact, if all of the standard exception classes had the same pattern of constructors, it would amount to a *simplification*. Right now they are evidently not 100% consistent with one another, and it's causing at least one user a spot of awkwardness.
Patricia Shanahan - 11 Jul 2007 00:41 GMT >>Implementing every requested feature, without questioning the tradeoffs >>involved, would be an absolute disaster for future maintainability of >>any computer program or programming language. > > One could argue that it's the user's own darn fault for requesting so > many features if the system then becomes a feeping creature. :) The problem is that most useful systems have more than one user. Any one user may have a couple of enhancement ideas each of which would be a good thing. A few thousand users may have thousands of ideas.
Even assuming a single user, someone has to make the cost benefit trade-off. If the user is going to make the trade-off, they need to be informed of the costs before making their final decision. Again, the change should not be made just because it has been requested, without some discussion of the reasons for not doing it.
> More significantly, in this specific case we're talking about adding > one constructor to one library class, hardly a major change or [quoted text clipped - 3 lines] > consistent with one another, and it's causing at least one user a spot > of awkwardness. The particular change under discussion indeed seems far more reasonable than suggestion that all requested changes should be implemented without even questioning their usefulness.
Patricia
Twisted - 11 Jul 2007 22:29 GMT > The particular change under discussion indeed seems far more reasonable > than suggestion that all requested changes should be implemented without > even questioning their usefulness. It was more of a question than a suggestion, but still it is also the case that if users seriously want something, and one vendor does not provide it, a competitor will be all too happy to ... and this is why "the customer is always right" when it comes to product functionality.
Roedy Green - 11 Jul 2007 01:25 GMT >Implementing every requested feature, without questioning the tradeoffs >involved, would be an absolute disaster for future maintainability of >any computer program or programming language. It is the programmer's (designer's) job to glean from the users' request just what the problem is he is having and come up with a solution.
The users have no clue HOW the problem is best solved.
I find it highly useful for a programmer to actually USE the code in production over a day or two as a humble clerk. He will see all kinds of opportunities for improvement a naive user would not think to ask for.
I remember doing a banking system back in the 70s. The users were asking for all kinds of things that were extremely hard for computers to do but were easy for humans. The users were asking for what they thought would be EASY, not useful. The were astounded to learn that it is trivially easy to maintain lists is several different orders at once. They never dreamed of asking for the "impossible". -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Twisted - 11 Jul 2007 22:33 GMT On Jul 10, 8:25 pm, Roedy Green <see_webs...@mindprod.com.invalid> wrote:
> The users have no clue HOW the problem is best solved. [snip rest]
This is the sort of elitism that is a rampant problem in IT these days. The whole attitude that "the users are clueless", and the accompanying baggage of user-hostility, tricking the users, ripping off the users, keeping the users in the dark and fed sh.t according to the mushroom theory of customer relations, patronizing and belittling the users, ignoring the users, dedicating entire layers of organizational structure to insulating the management from the users from making "webmaster@" bounce to setting up an elaborate referral- maze in the phone PBX to ensure that nobody who calls your obligatory 800 number ever actually reaches a live human being with their complaint or feedback or request for support or information ...
I have little sympathy for IT types that show brazen disrespect for the users, who are often the customers that ultimately pay them, and whose needs they certainly are being paid to provide for according to their job descriptions...
Martin Gregorie - 12 Jul 2007 00:25 GMT > On Jul 10, 8:25 pm, Roedy Green <see_webs...@mindprod.com.invalid> > wrote: [quoted text clipped - 4 lines] > This is the sort of elitism that is a rampant problem in IT these > days. I don't see Roedy's comment that way at all.
Is a concert goer clueless if he can't play a guitar solo? Is a driver clueless if he can't diagnose a fuel injection fault? Is an accountant clueless because he can't improve an SQL query?
I don't think so.
Suggesting that they are clueless is elitism, but that is twisting the argument. Nobody was suggesting that.
OTOH suggesting that they know as much as an IT professional and hence are equally capable of specifying a system change falls into exactly the same trap as the post modernists when they say that because everybody's opinion about art and other soft subjects is equally valid the same must apply to science, engineering, etc.
 Signature martin@ | Martin Gregorie gregorie. | Essex, UK org |
Patricia Shanahan - 12 Jul 2007 01:14 GMT >> On Jul 10, 8:25 pm, Roedy Green <see_webs...@mindprod.com.invalid> >> wrote: [quoted text clipped - 10 lines] > Is a driver clueless if he can't diagnose a fuel injection fault? > Is an accountant clueless because he can't improve an SQL query? I think it is very important that someone consider the cost/benefit trade-off for any change. That can be the user, especially if the program has a single user, but in that case they need to be informed of the costs.
It can be the developers, but they would need to learn about the benefits, and that is unlikely to happen if they are not allowed to ask the users any questions about the use of a proposed feature.
Patricia
Twisted - 12 Jul 2007 06:10 GMT > >> On Jul 10, 8:25 pm, Roedy Green <see_webs...@mindprod.com.invalid> > >> wrote: [quoted text clipped - 19 lines] > benefits, and that is unlikely to happen if they are not allowed to ask > the users any questions about the use of a proposed feature. I think I should clarify my original position. There's two things IT professionals do that are somewhat related, only one of which is objectionable.
One is to believe they know best about implementing the solution or administering the system or similarly in order to enable the users to achieve their goals. In this, they are right, assuming they are competent to do their jobs.
The other is to believe they know better than the users what the users should want or what the users' goals should be. This is when they are being disrespectful to the users, and ultimately are liable to betray the trust the users placed with them. This is unfortunately all too common and sometimes (not always with a true and serious cause) catch a whiff of it around here, and elsewhere on the net.
(The really, really evil ones know full well what the users' goals are and don't *care*; these ones care about how they can interfere with users achieving their goals in order to extort from them, or how they can foist advertising before their eyeballs despite their wishes not to be bothered, and suchlike. In this group we count the numerous spammers, spyware vendors, adware crafters, devisers of DRM, and suchlike. Bombers and cripplers of software; nagware authors; anyone who tries to extort or annoy fees out of someone whose continued activities don't require their services or therefore cost them any money; anyone who distorts the architecture of a system to make the users need services from them that they could as easily have been able to do without, e.g. telcos that design phone systems to go through a centralized system, thereby costing the telcos when used, thereby granting the telcos a reason to charge money for every minute of call time, specifically designing them to be incapable of routing calls through an ad-hoc network simply because this would give the users more and cost less, so they would not be able to charge very much money at all. This last is a crime against efficiency and, in these days of climate disturbance and dwindling oil supplies, that makes it quite simply a crime. Ad-hoc-capable phones would have saved thousands in New Orleans which compounds the telcos' crime in deliberately crippling the cellular telephone technology's potential to maximize their own revenues. Of course, the cellular oligopoly is seeing upstart competition now from new kinds of wireless tools, with the likelihood that it will soon prove that their design decisions were also criminal with respect to their long-term fiduciary obligations to their stockholders on top of everything else...
IT types that deliberately stand athwart user goals for reasons of greed I liken to the old tales of trolls under bridges. Either they didn't build the bridge at all, or the costs of construction were long since paid and the maintenance costs are minimal, yet they insist on extorting a fat toll from every traveler to cross. With any kind of pay software we can observe the nearby "open source" bridge, whose builders toiled without recompense to construct it, then set up shop near the bridge knowing to benefit from all the traffic as merchants, and end up making plenty of money and earning far more goodwill from travelers besides. From time to time they maintain their bridge out of a fraction of their revenues as merchants, knowing its collapse would end their profitability. Then the trolls appear not only greedy but foolish and lacking in business sense besides.)
Oliver Wong - 12 Jul 2007 23:49 GMT >> >> On Jul 10, 8:25 pm, Roedy Green <see_webs...@mindprod.com.invalid> >> >> wrote: >> >>> The users have no clue HOW the problem is best solved. [...]
>> >> This is the sort of elitism that is a rampant problem in IT these >> >> days. [...]
> I think I should clarify my original position. There's two things IT > professionals do that are somewhat related, only one of which is [quoted text clipped - 11 lines] > common and sometimes (not always with a true and serious cause) catch > a whiff of it around here, and elsewhere on the net. I think there's another relevant thing that IT people do: believe that sometimes client is unable to express what they want.
There's a lot of absolutes being thrown about in this thread, so I'd like to address that before coming back to my main point. *USUALLY* the IT person in charge of a given IT project knows more about computers than the client paying for the project. Usually. Not always. Usually the IT person knows more about programming than the client; but not always. Usually the IT person knows more about software design than the client; but not always.
Sometimes, the client is a really smart programmer/software-architect/engineer/whatever who just happens to be hiring someone to do an IT project for them, and the person they are hiring is less skilled than they are. It could simply be that the client has more important projects to take care of, and just needs some bodies to finish off the easy parts of a nearly complete project. Here, the client knows more about computers/programming/etc. than the programmer.
For the rest of this post, I'm going to be talking about the more common case where the client is someone who knows very little about computers, and just wants to throw money at someone who'll take care of all the details, as long as they get what they want.
But again, sometimes the client is unable to express what they want. And sometimes one of the IT people has, as a primary function, to extract from the client exactly what it is that they want specifically because clients have so much trouble expressing what they want.
Let's say the client, familiar with math, statistics, game design, literature, etc. but not very familiar with computer science, says "I want to make a game, and as a first step I want a random number generator that will give me a uniform distribution of all possible values between 0 and 1". Well, the client is almost surely mistaken. The vast majority of numbers between 0 and 1 are uncomputable (that is, they have an Kolmogorov-Chaitin complexity of infinity, and cannot possibly be generated by a Turing Machine). Much more probably, what the client "really" wants is for all IEEE double values between 0 and 1 being generated with equal probability.
So now, the IT person, who has been sent as a liaison/interpreter between the clients and the programming team, has a choice of what to do. Do they tell the client that their request as stated is impossible to satisfy, lecture them about the size of the set of integers and reals, IEEE standards, Turing Completeness and so on, or do they just assume they know better than the user what they really want, and jot down "Random Number Generator, 0.0 <-> 1.0" on their task list, and move on to the next set of requirements?
Again, there's a bit of context involved: If the client's project has something to do with encryption or online gambling or stuff like that, then you might need to probe the for more details, such as whether a "truly random" generator is required (and you might get into philosophical debates about the definition of "truly random"), or if whether Java's built in pseudo-random number generator is "good enough". But if they're just making a single player game, you can generally assume that a PRNG is what the client really wants.
A part of "doing what the customer wants" is usually "don't bug the client too much with the details". If the client knew all the details of how to do what they wanted to do, they'd probably just do it themselves (with the exceptions mentioned above).
Clients (and people in general) also tend not to be very good at judging what parts of their request require a lot of detail, and what parts are best left up to the whims of the developers.
The end goal of everybody is to become happier. If you tell a software developer to write software that will make the client happy, the software developer is probably going to complain that the request is too vague, and outside of the dev's area of expertise. The client needs to do some analysis of their own to determine (perhaps correctly, perhaps incorrectly) that being rich will make them happy, that having more profits and fewer expenses will make them rich, and that it must be possible software will increase profits and reduce expenses. Now we're getting closer to the point where a software dev can come in handy.
At the other extreme, the client may give requirements that are overly specific, that they don't really care about, and that make the developer's life more difficult, simply because they felt that they should give lots of specific details (perhaps because in the past, they had received complaints that their requirements were too vague).
As an example of this, a client may state that they want an HTML document to be generated which has very specific formatting requirements when printed; for example, with a specific footer appearing on the first page, and a different footer appearing at the bottom of every other page.
In theory, this is possible: We could try develop some sort of spyware which would secretly get executed on the end user's computer, accurately detect the browser and OS being used (can't trust the agent-string sent in), and the size of the paper in the printer's tray, and force-configure the printer margins to be a specific setting (e.g. 0.3 inches), and then use lots of <div> tags and CSS hacks to exactly position elements on a pixel-by-pixel basis. We'd have to generate different HTML and CSS combinations for every OS, browser and paper size combination (and there are over 500 versions of Firefox for Windows alone, so this is quite an explosive combinatorics equation). If we're going to be installing spyware on the user's computer, why don't we just have the spyware directly communicate with the printer, you ask? Well, the user *said* they wanted an HTML document generated, and for that HTML document to get printed.
Instead, we asked them if we could just generate the document as PDF instead of HTML. It turns out that we could, and the client didn't really care either way. Made our lives a lot easier.
- Oliver
Twisted - 13 Jul 2007 02:55 GMT > So now, the IT person, who has been sent as a liaison/interpreter > between the clients and the programming team, has a choice of what to do. [quoted text clipped - 4 lines] > Number Generator, 0.0 <-> 1.0" on their task list, and move on to the next > set of requirements? This doesn't bug me. There's nothing arrogant or condescending involved here; just interpretation that seems reasonable.
> Again, there's a bit of context involved: If the client's project has > something to do with encryption or online gambling or stuff like that, [quoted text clipped - 4 lines] > just making a single player game, you can generally assume that a PRNG is > what the client really wants. Terrible idea. Java's built in PRNG is an LCG, which isn't simulation grade. Too high correlations between random N and random N+K for some small choices of K. If you want a PRNG in a game you want Mersenne Twister, which is fairly fast and efficient and is simulation grade.
It does make sense to ask the client if they want repeatability and if they want a cryptographically secure one. Repeatability requirements rule out using hardware noise or "entropy pool" RNGs. Cryptographic grade suggests using Java's SecureRandom, or using an LCG to discard random numbers of sequential results from another LCG, both with long repeat times and large prime ratios involved. (This prevents exposing the N+K correlation in e.g. session keys, ID numbers, or other exposed data which otherwise might allow someone to guess the next number after seeing a few and crack or spoof something. SecureRandom might already work this way, or it might be a more complex scheme; I don't know much about its internals.) So there may certainly be cases where you need to get requirement information from the client. They might not really know whether they need simulation-grade or secure or some such random numbers. I'd ask them a bit about the game. If it's a shoot-em-up MT is probably best. If it's online poker, with fewer randoms needed but money riding on those randoms being unguessable in advance, I'd use a cryptographic-grade RNG even if it meant it was slower. If repeatability wasn't needed but unguessability was crucial, I might use an entropy pool or a hardware RNG -- a stand-alone poker terminal could include a hardware RNG; PC software probably can't; an online poker server can get entropy pool effects by sharing a single good and fast RNG among all connected sessions, so you could not guess the next shuffle at any one virtual table without monitoring ALL the virtual tables, but the RNG has to be damned fast in this case, and the server should preshuffle the next few virtual decks concurrently (though thread-safely) to ensure the RNG state is thoroughly mixed with all of those shuffles, then use those decks when fresh shuffled decks are needed by a connected session, keeping a queue of shuffled virtual decks to use. This implies a backend service that acts as a shuffled-deck factory, possibly on fast dedicated hardware in the poker company's back office. This might even have added physical security and access restrictions, depending on the stakes involved. (And the backend has to validate cards somehow in this case, or the deck can be tampered with undetectably after it leaves the black box. The other major way to cheat, peeking at someone else's cards, needs wholly different sorts of security to defeat, such as cryptography on client connections. Stopping players from "teaming up" in online poker and consensually sharing information through back-channels is probably not even feasible.)
Of course, a high-stakes online poker company should probably invest in some in-house security expertise of its own to make recommendations about implementation of sensitive parts of the system!
Piotr Kobzda - 10 Jul 2007 15:44 GMT > On Jul 10, 1:10 am, dvdav...@pobox.com wrote: >> IllegalArgumentException implements the (relatively) new contructors [quoted text clipped - 3 lines] > I guess they forgot it, or just haven't gotten around to it yet. > Submit it to Sun's bug tracker and they'll probably have it in Java 7. That could be RFE at best, not a bug report.
Quote from Throwable Javadoc:
"Further, as of release 1.4, many general purpose Throwable classes (for example Exception, RuntimeException, Error) have been retrofitted with constructors that take a cause. This was not strictly necessary, due to the existence of the initCause method, but it is more convenient and expressive to delegate to a constructor that takes a cause."
More there: http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html
Just to summarize that, the solution for the OP's problem (already mentioned also by Lew in this thread) seems to be:
... } catch (NumberFormatException e) { throw (NumberFormatException) new NumberFormatException("new message").initCause(e); }
piotr
dvdavins@pobox.com - 10 Jul 2007 16:35 GMT
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 ...
|
|
|