gpt4 book ai didi

java - 使用父类(super class) java 进行异常处理

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

如果我想使用父类(super class)来处理异常,我还需要使用 try catch 来处理异常吗?这是父类(super class)和我用来测试它的类的代码。我尝试在测试类中使用方法商,但我需要添加一个 try catch 语句来执行我想要它执行的操作。

 public class ExceptionA {




public static int quotient(int numerator, int denominator)
throws ArithmeticException
{
return numerator / denominator; // possible division by zero
}


}

public class ExceptionTest {


public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
boolean continueLoop = true;




do
{
try
{
System.out.println("Please enter an integer numerator");
int numerator = scanner.nextInt();
System.out.println("Please enter an integer denominator");
int denominator = scanner.nextInt();

int result = ExceptionA.quotient(numerator, denominator);
System.out.printf("%nResult: %d / %d = %d%n", numerator,
denominator , result);
continueLoop = false;
}
catch ( ArithmeticException arithmeticException)
{
System.err.printf("%nException: %s%n" , arithmeticException);
System.out.printf("Zero is an invalid denominator. Please try again."
+ "%n%n");
}

} while(continueLoop);

}
}

最佳答案

如果该方法抛出异常,那么您要么必须编写抛出异常的方法,要么使用 try/catch 来处理异常。在某些时候,您将不得不使用 try/catch,特别是当您在 main 方法中调用代码时。

关于java - 使用父类(super class) java 进行异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163153/

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