Home > Mobile >  if statement is not working inside of try and catch
if statement is not working inside of try and catch

Time:12-20

I wrote a program to only accept even numbers and catch an exception if it is not an even number when I enter an even number the code prints it but when I entered an odd number nothing happened

and whenever I try and add else red lines cover the whole block

Scanner input = new Scanner (System.in);
System.out.println("Please enter number :  ");
int number = input.nextInt();
        
try{
    if(number%2 == 0){
       System.out.println(number);
    }
} 
catch(Exception  e){
    System.out.println("this input is not an even number");
    e.printStackTrace();
}

CodePudding user response:

This is an odd place to use an Exception. You could use an Exception to indicate the value is odd, like

try {
    if (number % 2 == 0) {
        System.out.println(number);
    } else {
        throw new Exception(String.format("Input %d is not even.", number));
    }
} catch (Exception e) {
    System.out.println("this input is not an even number");
    e.printStackTrace();
}

But, you still need an else. And that would be a far more appropriate place to handle the odd value (no Exception neccessary). Like,

if (number % 2 == 0) {
    System.out.println(number);
} else {
    System.out.printf("this input %d is not an even number%n", number);
}

CodePudding user response:

As you guessed, the logic should be in an else block, not the catch block:

try {
    if (number % 2 == 0) {
        System.out.println(number);
    } else {
        System.out.println("this input is not an even number");
    }
} catch(Exception e) {
    e.printStackTrace(); // Or some other more robust exception handling
}

CodePudding user response:

You tried to catch thrown exceptions. But you rather should throw an exception. (And probably later catch it.)

 if (number % 2 != 0) {
     throw new IllegalArgumentException("Not an even number: "   number);
 } 
 System.out.println(number);

There are two RuntimeExceptions most suited:

  • IllegalArgumentException when the passed data is wrong;
  • IllegalStateException when the state (calculation) is wrong.
  • Related