2016-07-06 139 views
0

如果这个问题看起来太愚蠢或者基本不好,我提前表示歉意。但谷歌搜索没有让我知道这一点。应该抛出或捕捉哪个异常

的代码很简单:

public class Average3 { 
    public static void main(String[] args) { 
    try { 

     printAverage(100, 0); 

    } catch (ArithmeticException ae) { 

     ae.printStackTrace(); 

     System.out.println("Exception handled in " + 
     "main()."); 

    } 
    System.out.println("Exit main()."); 

    } 

    public static void printAverage(int totalSum, int totalNumber) { 
    try { 

     int average = computeAverage(totalSum, totalNumber);// (8) 
     System.out.println("Average = " + 

      totalSum + "/" + totalNumber + " = " + average); 
    } catch (IllegalArgumentException iae) { 

     iae.printStackTrace(); 

     System.out.println("Exception handled in " + 
     "printAverage().");   
    } 
    System.out.println("Exit printAverage()."); 

    } 
    public static int computeAverage(int sum, int number) { 
    System.out.println("Computing average."); 

    return sum/number; 

    } 
} 

输出:

Computing average. 
java.lang.ArithmeticException:/by zero 
     at Average3.computeAverage(Average3.java:30) 
     at Average3.printAverage(Average3.java:17) 
at Average3.main(Average3.java:6) 
Exception handled in main(). 
Exit main(). 

这里我期待抛出:IllegalArgumentException由于被0除发生在computeAverage其通过printAverage调用。在我看来,try语句应该跳过,并且在这一点上它应该移动到注册IllegalArgumentException的catch处。

我其实有一个阴沉的了解,但我想知道到底发生了什么,为什么。我一直在绞尽脑汁。

感谢您的帮助。

+0

为什么它应该移动到'IllegalArgumentException'的'catch'? –

+0

,因为我认为try-catch块和try语句失败,它应该移动到捕获 – user6556673

+0

为什么你认为你在使用catch时提到一个异常类型?这种类型代表什么? –

回答

0

异常应在computeAverage被抛出和捕获在printAverage

0

computeAverage调用内部printAverage抛出ArithmeticException,你不处理。

因此不执行你的IllegalArgumentExceptioncatch语句,执行你的语句处停止:

System.out.println("Average = " + totalSum + "/" + totalNumber + " = " + average); 

...扔ArithmeticException

这会在您的main方法中发现,然后您在ArithmeticException上调用printStackTrace

因此,您可以希望catch ArithmeticExceptionprintAverage方法,而不是IllegalArgumentException(以及可能重新引发IllegalArgumentException,在ArithmeticException包装为根本原因)。

但是,最好的办法可能是首先检查你的论点,如果某些事情会导致0的分裂,则抛出IllegalArgumentException

+0

我现在明白了。谢谢。 – user6556673