How to implement java exception handling within a swtich-case?

Asked

Viewed 65 times

2

I have to do a treatment for possible exceptions within a calculator, one of them would be the division by 0, in the case "Arithmeticexception", but I’m not able to make it work, even after implementing the try-catch the code continues to return the default message and not the message I wrote on catch for that mistake:

case 4:
      if (num1 < num2){
       System.out.println("Impossivel realizar calculo!! \n");    
      }
      else 
      {
      int divide = num1 / num2;
      System.out.println("A divisao e: "+divide);
      }

      try{
      int divide = num1 / num2;
      System.out.println("A divisao e: "+divide);
      } catch(ArithmeticException e){
    System.out.println("Erro: divisão por zero!");
      }
    
      break;

1 answer

2


No need to treat the exception, do not let it occur, exception should only occur if it is something exceptional, you can prevent it from occurring then do it:

if (num1 < num2 || num2 == 0) System.out.println("Impossivel realizar calculo!!");    
else System.out.println("A divisao e: " + num1 / num2);

I put in the Github for future reference.

Even the code becomes much simpler.

This has nothing to do with switch other than by circumstance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.