捕获 ArithmeticException 但未按预期处理

Catching an ArithmeticException but not handling as intended

我对整个捕获处理异常概念有点陌生,我想知道为什么 throws ArithmeticException 在退出时不产生异常错误消息(在这个 case/by 中为零),但是而不是在编译期间。

不是应该能正常编译然后在屏幕上显示错误信息吗?我做错了什么?

public class Exception_Tester 
{ 
    public static void main(String args[]) 
    { 
         Exception_Tester et = new Exception_Tester(); 
         int x1; 
         int x2; 
         x1 = 5; 
         x2 = 0; 
         et.printResults(x1, x2); 
    } 

    void printResults(int a, int b) throws ArithmeticException 
    { 
         System.out.println("Add: "+(a+b)); 
         System.out.println("Sub: "+(a-b)); 
         System.out.println("Mul: "+(a*b));
         System.out.println("Div: "+(a/b));
    }  
} 

Checked Exception :如果您没有处理这些异常,这些异常将在编译时抛出错误。 Unchecked Exception : 如果你没有处理,你只会在运行时出错。

ArithmaticException 是未经检查的异常,因此您将在运行时得到异常。

如果您正在使用 try-catch 块,那么您必须使用

printStackTrace()

打印异常堆栈跟踪的方法。

如:

try{
    System.out.println("Add: "+(a+b)); 
    System.out.println("Sub: "+(a-b)); 
    System.out.println("Mul: "+(a*b));
     System.out.println("Div: "+(a/b));
}
catch(ArithmeticException e){
    e.printStackTrace();
}

看看下图:

如您所见,一些异常 class 以粗体显示以引起我们的注意。这是编辑对这些例外类别的解释

  • 在正确的程序中很容易出现的条件是已检查的异常。具体来说,这些异常是由编译器 <> 编译的,他可以正确地评估它们发生的可能性,并在相应的情况下声明编译错误。从图中可以看出,NullPointerException不直接属于这个类别:这些是直接扩展Exception class.

  • 的异常
  • 通常被视为致命的严重问题或可能反映程序错误的情况是未经检查的异常。

  • 致命情况由错误 class 表示。

  • 可能的错误由 RuntimeException class 表示。例如扩展 RuntimeException class 的异常就是这种情况。 NullPointerException 就是其中之一。在这种异常的大多数情况下,编译器无法评估它们将导致异常的@compile 时间,因为对应用程序的动态状态有很强的依赖性

这是一个简单的例子:

我创建了两个异常 class其中一个扩展了异常

public class Exception1 extends Exception {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

还有一个扩展 RuntimeException

public class Exception2 extends RuntimeException {

    private static final long serialVersionUID = 4595191052237661216L;

}

然后我有以下NewTester class

public class NewTester {

    public static void methodA() throws Exception1 {

        throw new Exception1();
    }

    public static void methodB() throws Exception2 {

        throw new Exception2();
    }

    public static void main(String[] args) {
        // methodA();
        methodB();
    }
}

我有意评论了对 methodA.In 的调用,这种状态你没有任何编译错误 因为调用的方法 methodB 抛出一个未经检查的 RuntimeException。但是,如果您通过取消注释对 methodA 的调用并注释对 methodB 的调用来更改此代码,您将遇到编译错误,因为 methodA 抛出已检查的异常

希望对您有所帮助

我按原样执行了你的代码

public class Exception_Tester 
{ 
public static void main(String args[]) 
{ 
 Exception_Tester et = new Exception_Tester(); 
 int x1; 
 int x2; 
 x1 = 5; 
 x2 = 0; 
 et.printResults(x1, x2); 
} 
void printResults(int a, int b) throws ArithmeticException 
{ 
  System.out.println("Add: "+(a+b)); 
  System.out.println("Sub: "+(a-b)); 
  System.out.println("Mul: "+(a*b));
  System.out.println("Div: "+(a/b));
}  
} 

它编译得很好,没有任何错误或异常,并且根据您的要求,只有在遇到 System.out.println("Div: "+(a/b)); 语句时,它才会在 运行 时间抛出 ArithmeticException。

所以我没有看到任何问题!