Why NumberFormatException is runtime?

Ilya.K picture Ilya.K · Aug 26, 2011 · Viewed 7k times · Source

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?

Answer

Bohemian picture Bohemian · Aug 26, 2011

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.