1

Integer.parseInt() in Java is declared to throw NumberFormatException, and it is a checked exception as I think. I have read somewhere that the checked exceptions should be either caught or thrown on the calling method. But we do not need to do it with NumberFormatException. I am confused. Please help me.

Anptk
  • 1,125
  • 2
  • 17
  • 28
khem
  • 21
  • 1
  • 1
  • 2

2 Answers2

5

Here is the regular code to use Interger.parseInt():

try {
    Integer.parseInt(string);
} catch (NumberFormatException e) {
    //code
}

But you could use the following (it catches all exceptions):

try {
    Integer.parseInt(string);
} catch (Exception e) {
    //code
}

Is that your question?

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Aditya Ramkumar
  • 377
  • 1
  • 13
0

It is not true that we do not need to check for NumberFormatExceptions.

A checked exception is an exception that could be thrown by a method you're calling and that you're checking for it and handling it appropriately. In the example you're giving, on NumberFormatException you might want to let the user know that they provided an invalid number.

Basically all exceptions should be checked and handled.

benji
  • 606
  • 6
  • 12
  • Thanks for the answer, The function signature of parseInt() is: public static int parseInt(String string) throws NumberFormatException . I thought NumberFormatException is a checked exception so must be caught or declared to be thrown otherwise it produces compiler error. But with a little more research I found that It extends IllegalArgumentException and IllegalArgumentException extends RuntimeException. So not catching is not a compiler error.Is it true? – khem Dec 05 '14 at 04:38