使用超类 java 进行异常处理



如果我想使用超类来处理异常,我还需要使用 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);
 }
 }

如果该方法引发异常,那么您将不得不编写方法来引发异常,或者使用 try/catch 来处理异常。在某些时候,您将不得不使用 try/catch,尤其是在 main 方法中调用代码时。

最新更新