java - 当我期望代码简单地打印 "Error"时,为什么我的代码会抛出 ArithmeticException ?

标签 java exception operators divide-by-zero

我编写了一个程序,要求用户输入两个数字,如果第二个数字是 0,它应该会给出错误。但是,我收到了一个错误,如下所示。我有一个 if-else 语句,但它没有按照我的预期进行。我不确定我做错了什么。

public static void main(String[] args) {
    int x, y;
    Scanner kbd = new Scanner(System.in);

    System.out.print("Enter a: ");
    x = kbd.nextInt();
    System.out.print("Enter b: ");
    y = kbd.nextInt();

    int result = add(x, y);
    int result2 = sub(x, y);
    int result3 = multi(x, y);
    int result4 = divide(x, y);
    int result5 = mod(x, y);

    System.out.println(x + " + " + y + " = " + result);
    System.out.println(x + " - " + y + " = " + result2);
    System.out.println(x + " * " + y + " = " + result3);
    System.out.println(x + " / " + y + " = " + result4);
    System.out.print(x + " % " + y + " = " + result5);
}

public static int add(int x, int y) {
    int result;
    result = x + y;
    return result;
}

public static int sub(int x, int y) {
    int result2;
    result2 = x - y;
    return result2;
}

public static int multi(int x, int y) {
    int result3;
    result3 = x * y;
    return result3;
}

public static int divide(int x, int y) {
    int result4;
    result4 = x / y;
    if (y == 0) {
        System.out.print("Error");
    } else {
        result4 = x / y; 
    }
    return result4; 
}

public static int mod(int x, int y) {
    int result5;
    result5 = x % y;
    if (y == 0) {
        System.out.print("Error");
    } else {
        result5 = x % y;
    }
    return result5;
}

输出 我收到此错误..

Enter a: 10
Enter b: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero

最佳答案

你得到这个是因为当你除以 0 时,Java 会抛出异常。如果您只想使用 if 语句来处理它,请使用如下内容:

public static int divide(int x, int y){
   int result;
   if ( y == 0 ) {
 // handle your Exception here
 } else {
   result = x/y; 
  }
  return result; 
}

Java 还通过 try/catch block 处理异常,它运行 try block 中的代码,并在 catch block 中处理异常的处理方式。所以你可以这样做:

try {  
       result4 = divide(a, b);
}
catch(//the exception types you want to catch ){
     // how you choose to handle it
}

关于java - 当我期望代码简单地打印 "Error"时,为什么我的代码会抛出 ArithmeticException ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421342/

相关文章:

java - Jar 文件不起作用(它没有启动应用程序)

Java - 无异常地关闭 ServerSocket?

swift - &/and &% 从 Swift 语言中移除了吗?

PHP 求幂运算符优先级

ruby-on-rails - 在 Ruby 中, "=>"是什么意思,它是如何工作的?

java - WebRTC,捕获屏幕

java - 压缩 java 字符串(url)

java - Java中的跨进程同步

c# - 内部异常 C#

java - 初学者关于java异常的问题