Jesse Silverman wrote:The input validation exceptions we are discussing here are "RuntimeException" classes, right?
, which can be thrown by Integer.parseInt(String)
, is a subclass of RuntimeException
. Referring to the original post (and not the large quantity of tangential content following it), it mentions "validation of keyboard input". There's a lot of other situations where you might be given a String value and you want to convert it to a numeric (e.g. Integer
) value, but let's just consider that. (You might be getting the data from a text file or a spreadsheet cell or an HTTP request or you name it.)
The original post says that this conversion "could easily be handled without try or catch". It's true that you could write some code which converts String to Integer without too much difficulty, although String to Double is considerably harder. But really. Why should the beginner with two days of Java learning under their belt be required to do that as part of writing their code which wants to get a number from the console? Just dealing with getting input from the console is enough to drive some beginners to drink. And so we have the parseInt
and so on methods.
And of course when parsing a String value to a numeric value, you have to consider the possibility that there's going to be a problem because the input isn't a valid numeric value (for whatever "numeric" means in the current context). Languages without exceptions would have used various hacks to deal with that, but Java has exceptions built into the language and when exceptional situations occur then you should use exceptions to deal with them. This is in no way an anti-pattern, not in Java anyway. I don't see why errors in user input should be treated differently than errors with network connections or database queries.
But back to why NumberFormatException
is a runtime exception, whereas FileNotFoundException
is a checked exception: I have no idea why they did that -- as I just said or implied, I wouldn't have done it that way. Finding non-numeric data in Strings which are only supposed to contain numeric data is not a programming error, like using a null value where it shouldn't be found or using an array index which points outside the array. Those things can be checked simply by code and avoided, so they can be classified as programming errors, but checking data for numericness is not simple to do and it's not reasonable to expect the programmer to write code which does that.