1
如果我想用超類來處理異常,我還需要使用try catch來處理異常嗎?這是超類和我用來測試它的類的代碼。我試圖在測試類中使用方法商,但我需要添加一個try catch語句來完成我想要的操作。使用超類-java處理異常
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);
}
}
main可以拋出一個異常就好了 –
是否可以在超類的方法中使用try catch或是否需要在main方法中再次調用它? –
你想在你打算處理錯誤的地方使用try/catch。這應該在調用方法中完成,而不是超類。你會想在主要方法中調用try/catch。 – BlackHatSamurai