Derry
Derry

Reputation: 371

Why won't this method print the message in the exception parameter?

I'm writing a method that is supposed to convert a string to an int if possible, and it throw an exception of not possible with a message. It throws the exception but it doesn't print the message, meaning it acts identically as it would were I to comment out the exception condition:

private static int throwsMethod() throws NumberFormatException{
    Scanner s = new Scanner(System.in);

    System.out.println("enter a number");
    String intNumber = s.next();

    Integer wrapperIntNumberConv = Integer.parseInt(intNumber);

    if(!(wrapperIntNumberConv instanceof Integer)){
        throw new NumberFormatException("can't make an int");
    }

    int fullConvertedNumber = (int) wrapperIntNumberConv;
    System.out.println(fullConvertedNumber);
    return fullConvertedNumber;
}

how can I do it without a try/catch block (I'm trying to learn exceptions and in this exercise, without a try/catch block) and get it to show the message?

edit: the reason the suggested answer that azro put in didn't solve my problem is because nothing there addreses a method with a throws someException() in the header

Upvotes: 0

Views: 927

Answers (2)

juzraai
juzraai

Reputation: 5953

The exception is probably thrown at this line:

Integer wrapperIntNumberConv = Integer.parseInt(intNumber);

Because parseInt itself throws it if the string does not contain a parsable integer. (Documentation)

So the program does not reach your if in that case.

You need to wrap the line with parseInt inside a try-catch block to be able to throw an exception with your message:

String intNumber = s.next();
try {
    return Integer.parseInt(intNumber);
catch(NumberFormatException e) { // catch system's exception
    // throw new one with your message
    throw new NumberFormatException("can't make an int");
}

Or, you can check if the string contains a number (optional sign and digits), before calling parseInt:

String intNumber = s.next();
if (intNumber.matches("-?\\d+")) { // see: regular expressions
    return Integer.parseInt(intNumber);
} else {
    throw new NumberFormatException("can't make an int");
}

Upvotes: 3

DanB
DanB

Reputation: 57

I'm not sure to understand what you want: if the NumberFormatException is thrown, it can't reach the print instructions

int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;

so no message is printed.

If you want to print the "can't make an int" message you can print it before throwing the Exception or in the caller method via try-catch

Upvotes: -1

Related Questions