是否需要Java异常构造函数?

时间:2013-12-13 02:46:44

标签: java exception exception-handling constructor unhandled-exception

我只是在Java中处理异常处理。 我的问题是: 代码中是否需要异常构造函数才能处理异常或 try-catch-finally块应该足够了?我这样说是因为,运行下面的程序。输出是相同的,在商(int number1,int number2)方法中有或没有THROW语句。以下是输出: 运行:


输入两个整数: 9 0 例外:整数不能除以零 在异常处理之后,程序继续......


public class ExceptionHandling {
    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(number1 + "/" + number2 + " is " + number1 / number2);

        }
        catch (ArithmeticException ex) {
            System.out.println("Exception: an integer cannot be divided by Zero");
        }

       System.out.println("After the exception handling, the program continues....");

    }


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

        return number1 / number2;

    }

}

1 个答案:

答案 0 :(得分:1)

使用或不使用throw语句时输出相同的原因是,当您将数字除以零时,Java已经抛出ArithmeticException的实例。只有你抛出不同的例外,你的情况才有意义。

  

public class ArithmeticException extends RuntimeException

     

发生异常算术条件时抛出。对于   例如,一个整数“除以零”会抛出此类的实例。   ArithmeticException对象可以由虚拟机构造   好像抑制被禁用和/或堆栈跟踪没有   可写的。