Search code examples
javaexceptionthrow

How to get rid of output "java.lang.Exception


I have some simple code that I wrote but I don't understand why the output is the way it is.

Here's the code:

public static void main( String args[] )
{
    // ADD LOOP CODE, ADD TRY CATCH BLOCK(S) AS NEEDED BELOW
    // BE SURE TO LEAVE THESE 3 LINES IN THERE SOMEWHERE  
    // SINCE THEY CONTAIN THE EXACT EXPECTED OUTPUT TEXT

    Scanner kbd = new Scanner(System.in);
    int a = 0;
    String token;
    do
    {
        try
        {
            System.out.print("Enter int in range 1..100 inclusive: ");
            token = kbd.next();
            a = Integer.parseInt(token);
            if(a < 1 || a > 100) throw new Exception("Number:" + a + " out of range. Must be in 1..100");
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Input was not an integer");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
    while(a < 1 || a > 100);
    System.out.format("Thank you. You entered %d\n", a );

    kbd.close();

}

And here's the output:

Enter int in range 1..100 inclusive: -2

java.lang.Exception: Number:-2 out of range. Must be in 1..100

Enter int in range 1..100 inclusive: f

Input was not an integer

Enter int in range 1..100 inclusive: 3

Thank you. You entered 3

What I don't understand is why the general exception is throwing "java.lang.Exception: " before the desired output of "Number: a out of range. Must be in 1..100" Is there some way to get rid of this part of the output?


Solution

  • You are throwing a java.lang.Exception so that is what is caught and that output is just the format of the exception's stdout. If you simply wish to print your string, just do

    System.out.println("Number:" + a + " out of range. Must be in 1..100");
    

    in the if statement block, because your while loop already catches the same condition, so the exception is redundant. i.e. you already check if the number is outside the range