Why NumberFormatException is runtime?
Asked Answered
S

6

29

Runtime exceptions indicate broken contract (like NPE) and should never be thrown if code has no errors. It always indicates error in code (same as asserts but asserts are for internal class errors while Runtime are for class's client errors).

Runtime exceptions should never be catched.

Checked exceptions, on the other hand, are part of signature and should be catched and processed. They may indicate user input errors or external resource troubles (like IOException).

With all of it I can't get why NumberFormatException is runtime?

Seth answered 26/8, 2011 at 13:47 Comment(3)
Like the way the Compiler doesn't know an object is null when something is operated on it, it doesn't know if the String that's parsed is actually a Number or not. It's an exception that is bound to occur only during the runtime.Destinee
@Roflcoptr: He's asking why NumberFormatException is a Runtime exception, not why he's getting one.Turn
@Destinee - same is true for other Exceptions and they still are not RuntimeExceptions. Example IOException when a Socket is close while reading. I don't think it is related to what the Compiler knows or not...Bittner
J
9

Firstly, whoever told you

Runtime exceptions should never be caught

doesn't know much about Java. Don't listen to them - they are wrong.

NumberFormatException being a runtime exception: Unchecked exceptions are chosen because they indicate a programming error. It is possible to know before calling Integer.parseInt() (for example) that a String is a valid integer number, e.g. here's just one way:

if (str.matches("^\\d{1,8}$") {
    int myInt = Integer.parseInt(str); // will never throw NumberFormatException 
}

Therefore, it can be considered a programming error to ever get one - the programmer chose to not check first.

If you are not confident about the integrity/quality of the String you are about to parse, it's easy to catch:

try {
    // parse your string
} catch (NumberFormatException e) {
    // do something about it
}

The other reason to make it a runtime is that it doesn't clutter the code with potentially unnecessary try/catch blocks, if you are confident that you won't get one, e.g. if to totally trust the source of the String data.

Joshia answered 26/8, 2011 at 13:51 Comment(12)
However, the same could be said of some checked exceptions like URLFormatThingyException and what have you. In short, it's all a bit of a mess.Audi
and the same - checking beforehand - could also be said about NPE!Bittner
absolutely! I always check for NPE: if (str != null && ...) etcJoshia
Integer.parseInt("-1"); // D'oh! - No, don't repeat the parsing code in your code, that defeats the whole point of a library. Null checks are trivial so they're allowable (up to a point). Jörn's answer suggests using the text parsing API instead, which seems more appropriate in this case.Hash
Is there any way to reasonably allow "2147483647" while disallowing "2147483648", without having to do as much work as would be necessary to simply parse the value?Raisin
@Raisin the only other realistic alternative would be to use regex, but it would be a shocker, and I'm not sure it would be less "work"?Joshia
The answer would be more convincing if there was a simple method to check the string before calling Ingeger.parseInt(). Calling String.matches() like that is fragile and probably an internationalization problem.Liter
The logic used in this answer is not convincing. Many exceptions can be prevented by checking a condition manually beforehand, however, that partially defeats the purpose of the method. On one hand, it requires an exact re-implementation of the method's internal check (thus a violation of encapsulation), on the other it adds useless runtime cost. What I could imagine instead is that the Java designers considered this example a border case (it may be a programming error), and aware of the annoyance of ever-present checked exceptions, decided against them.Arquit
By the way, Guava has Ints.tryParse() that returns null instead of throwing an exception on invalid values.Announcer
“In particular, exceptions of the Error or RuntimeException classes or any of their subclasses do not have to be listed in your throws clause. They get special treatment because they can occur anywhere within a Java program and are usually conditions that you, as the programmer, did not directly cause.” - Sams Teach Yourself Java in 21 Days (Covers Java 11/12), 8th Edition. [Exceptions and threads section]Grammer
@Grammer That's exactly wrong. RuntimeExceptions are (at least supposed to be) programmer mistakes. Checked exceptions are external things the programmer didn't cause.Isley
@Grammer it would seem that “Sam” doesn’t know what here’s talking about. RuntimeExceptions are “all the programmer”, and even some Errors (eg OutOfMemoryError - who used all the memory???). No - Sam is completely wrong. The reason they are unchecked the caller should not be required to handle them because they are unrecoverable (nothing you can do about it) or avoidable (due to programmer error - why should a coder have to deal with another coder’s stupidity?!).Joshia
X
2

NumberFormatException could also be thrown when parsing configuration files, in which case it would be a programmer error. When parsing user input you are usually using NumberFormat which throws a checked ParseException.

Xenophobe answered 26/8, 2011 at 13:53 Comment(2)
Configuration files are not always (or even often) under the programmers control, but I think your point is well made. The Java libraries provide distinct APIs for handling input from a trusted source vs input from an untrusted source.Hash
yes! got lucky and found this answer, this explains why NumberFormat thrwes a checked ParseException, while Integer.parseInt throws a runtime exception. good point about the config files, that is I believe exactly how it was designed and meant to be used - NumerFormat for user input, Integer.parseInt for all the restWoodrum
P
1

NumberFormatException extends IllegalArgumentException. The reason why this is a runtime exception is that it is completely possible to break the contract of a method that takes a String and returns a Number. If I pass in 123D and there is not a proper validation of data than this would be an appropriate illegal argument.

Petrochemistry answered 26/8, 2011 at 13:52 Comment(0)
C
-1

Why is NumberFormatException a runtime error? Well if you have a dialog where the user enters a value, and the value is not a number but is parsed as such then you would want to know about that. Is an exception the best way? Perhaps not, but it is what it is.

Coddle answered 26/8, 2011 at 13:51 Comment(1)
I believe the question is about it being a subclass of RuntimeException instead of an simple Exception, that is not being a checked exception.Bittner
I
-2

In a sense, NumberFormatException is a compile-time exception. But instead of being thrown by the Java compiler, it's thrown by the format string parser/compiler when your program runs it. The same applies to Pattern and other uses of regular expressions; your program is running the parser/compiler.

Isley answered 15/11, 2015 at 19:29 Comment(0)
C
-2

I think runtime exceptions happen when the hardware of the computer does an operation, then realizes that it's not possible, so it's too late to go back and throw an exception, so the program crashes. for number format exception, the computer tries to read, for example, a string as an int. The hardware tries to store a char in an int variable , which is not possible. basically anything that involves hardware, like division over 0

Coppock answered 6/7, 2020 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.