Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 337
user1279780 Avatar asked Jan 16 '23 19:01

user1279780


1 Answers

Since this is homework, I'll just give you a hint: you have to call the method, and surround the call with an appropriate try-catch block.

like image 127
NPE Avatar answered Jan 20 '23 16:01

NPE