【问题标题】:Are Java Exception constructors required?是否需要 Java 异常构造函数?
【发布时间】:2013-12-13 10:54:53
【问题描述】:

我刚刚开始接触 Java 中的异常处理。 我的问题是这样的: 代码中是否需要异常构造函数才能处理异常,或者 try-catch-finally 块就足够了?我这么说是因为,运行下面的程序。输出是相同的,无论是否在 quotient(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;

    }

}

【问题讨论】:

  • 如果你打算显式抛出它,你只需要构造一个异常。您可以捕获一个异常,而无需您自己使用构造函数(尽管系统在内部使用一个构造函数来创建它抛出的异常)。

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


【解决方案1】:

无论是否使用 throw 语句,输出都相同的原因是,当您将一个数字除以零时,Java 已经抛出了 ArithmeticException 的实例。只有抛出不同的异常,您的条件才有意义。

公共类 ArithmeticException 扩展 RuntimeException

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

【讨论】:

  • 感谢大家的意见。我现在明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 2021-05-25
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多