Search code examples
javaparseintnumberformatexception

How do I trap NumberFormatException thrown by parseInt


I am stuck on this question~:

The method Integer.parseInt converts a String of digits to the int number it denotes.

public static int parseInt (String s)
             throws NumberFormatException

Explain how you could trap the exception thrown by parseInt and illustrate your answer with a code example.

My answer that I have thought of so far is:

try
{
   System.out.println("incorrect");

}

catch (NumberFormatException n)
{
   System.out.println("WRONG! This is not a number");
}

I have a feeling this answer is wrong because the code above would only be used in the main method and I'm not sure how I would trap the exception under:

public static int parseInt (String s)
             throws NumberFormatException.

I've looked through java API for the parseInt method and looked via various research and tried doing the code, however I'm still struggling to get this right due to my lack of understanding.

If anyone could help me out, I'd be grateful, thanks in advance.


Solution

  • 
    String numStr = "15A";
    try {
      int num = Integer.parseInt(numStr);
    } catch (NumberFormatException nfe) {
      // not a number
    }