Hello all, My understanding is that its not a good practice to catch RuntimeExceptions, right?
Now if I have a String that is supposed to represent a number (an integer) and I want to check if the String is representing a valid number or not, what is the better way: 1. Using Integer.parseInt(str) and catch NumberFormatException (which is a RuntimeException, and should not be catched!)
2. Or implementing a utility method that checks every character in the String to see if its a digit or not, and return a boolean. (though this could be slower than the first way).
I realized that checking for digits may not be enough. So, I will modify our checking method to be:
This way, a String will be considered as representing an integer if: 1. All characters are digits. 2. The length of the String is less or equal ot the length of the MAX_INT. 3. char(i) of the String is "smaller" than char(i) of the MAX_INT.
(even though you could find other problems with this method, always there will be a work-around
Basically my question is: Is it better to use such a method, or use parseInt() and catch NumberFormatException. I know parseInt() is easier, less coding, and may be faster, but isn't bad to cacth RuntimeExceptions ?
Personally I always use parseInt and catch the NumberFormatException - it is reliable, simple and straightforward. I don't know how the "bad to catch RuntimeExceptions" meme got started but it is preposterous. This is exactly the kind of thing RuntimeExceptions are good at. I'm sure that anybody who had to unravel C code with special error return values will agree with me. Bill
Originally posted by William Brogden: Personally I always use parseInt and catch the NumberFormatException - it is reliable, simple and straightforward.
Ditto. I'd also extract that code into a helper method (returning a boolean), so that I wouldn't have to write it a second time ever.
I don't know how the "bad to catch RuntimeExceptions" meme got started but it is preposterous.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Zafer Abu saeed
Joined: Mar 28, 2004
Thanks! I will use the Integer.parseInt() method
(also I think writing a checking method is a sort of re-inventing the wheel).