1

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

它不应该正常编译然后在屏幕上显示错误消息吗?我究竟做错了什么?

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));
    }  
} 
4

3 回答 3

0

看看下面的图片:

例外类别

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

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

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

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

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

这是一个简单的例子:

我创建了两个异常类,一个扩展了 Exception

public class Exception1 extends Exception {

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

}

和一个扩展 RuntimeException

public class Exception2 extends RuntimeException {

    private static final long serialVersionUID = 4595191052237661216L;

}

然后我有以下 NewTester 类

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 的调用。在这种状态下,您没有任何编译错误,因为被调用的方法会methodB抛出未选中的 RuntimeException。但是,如果您通过取消注释对方法A 的调用并注释对方法B 的调用来更改此代码,您将遇到编译错误,因为方法A 抛出一个检查异常

我希望这有帮助

于 2015-04-17T19:05:04.377 回答
0

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();
}
于 2015-04-17T18:50:22.250 回答
0

我按原样执行了你的代码

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。

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

于 2015-04-17T19:29:19.120 回答