gpt4 book ai didi

java - Java 异常构造函数是否必需?

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:44 25 4
gpt4 key购买 nike

我刚刚开始接触 Java 的异常处理。我的问题是这样的:代码中是否需要异常构造函数才能处理异常,或者 try-catch-finally block 就足够了吗?我这么说是因为运行下面的程序。无论 quotient(int number1, int number2) 方法中是否包含 THROW 语句,输出都是相同的。以下是输出:运行:

<小时/>

输入两个整数:90异常(exception):整数不能除以零异常处理后程序继续......

<小时/>
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;

}

}

最佳答案

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

public class ArithmeticException extends RuntimeException

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class. ArithmeticException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

关于java - Java 异常构造函数是否必需?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com