如果我想使用超类来处理异常,我还需要使用try catch来处理异常吗?这是超类的代码和我用来测试它的类。我试图在测试类中使用方法,但我需要添加一个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);
}
}
答案 0 :(得分:0)
如果方法抛出异常,那么您要么必须编写方法来抛出异常,要么使用try / catch来处理异常。在某些时候,您将不得不使用try / catch,尤其是在您使用main
方法调用代码时。