0不能使用try和catch java进行划分

时间:2015-08-12 15:36:08

标签: java try-catch

如何让我的程序不允许用户除以零?如果除以零,程序将处理异常并显示消息“请输入另一个大于零的整数"使用try和catch

import java.util.*;

public class Calculation {
  public static void main(String args[] ){
    Scanner s = new Scanner(System.in);
    int num1 = 0, num2 = 0, answer;
    try {
      if (num1 == 0) {
        System.out.print("Enter first integer to be divided: ");
        num1 = s.nextInt();
        System.out.println("Please input another integer than zero");
      } else if (num2 == 0) {
        System.out.print("Enter second integer to be divided: ");
        num2 = s.nextInt();
        System.out.println("Please input another integer than zero");
      } else {
        answer = num1/num2;
        System.out.println("Answer is: " + answer );
      }
    } catch(Exception e) {
      System.out.println("Answer is: " + e.getMessage());
    }
  }
}

1 个答案:

答案 0 :(得分:0)

只需throw-catch Exception,例如建议的ArithmeticExceptioncreate your own

try {
    if(num2 == 0){
        throw new ArithmeticException();
    }
} catch (ArithmeticException e) {
    System.out.println("Please input another integer than zero");
}