Java Exception Handlng

时间:2015-10-11 01:46:21

标签: java exception-handling try-catch throw

我正在努力更好地理解异常处理。我已经阅读了我的书并用谷歌搜索了它,但这段代码对我来说没有意义。在进入此代码块之前我理解的方式是,如果用户输入无效数字或0,则throw new ArithmeticException将异常抛出到catch块,catch块会处理它,然后执行继续照常进行。当我运行此代码时,catch block中的代码将被执行,但不会执行throw new ArithmeticException代码。所以我的两个问题是,为什么throw new ArithmeticException代码也没有被执行,为什么同一个问题会显示两个不同的错误消息...?

import java.util.Scanner;

public class App2 {

    public static int quotient(int number1, int number2)
    {
        if (number2 == 0)
        {
            throw new ArithmeticException("divisor cannot be zero");
        }

        return number1 / number2;
    }

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        System.out.println("enter two integers");

        int number1 = input.nextInt();
        int number2 = input.nextInt();

        try
        {
            int result = quotient(number1, number2);
            System.out.println(result);
        }
        catch (ArithmeticException ex)
        {
            System.out.println("exception: integer can't be divided by 0");
        }

        System.out.println("execution continues");
    }
}

2 个答案:

答案 0 :(得分:1)

仅显示消息"divisor cannot be zero",因为抛出了异常。

如果异常被捕获,您只会看到此消息。您将在堆栈跟踪中看到它(错误消息)。

如果你摆脱了t​​ry-catch块然后尝试,那么你应该看到:

Exception in thread "main" java.lang.ArithmeticException: divisor cannot be zero

答案 1 :(得分:0)

您还可以删除以下代码:

    catch (ArithmeticException ex)
    {
        System.out.println("exception: integer can't be divided by 0");
    }

因为它已经在方法中表达并且是多余的。不影响代码。如果您想要清理代码,只是让您知道。

-Manny

相关问题