2017-04-01 40 views
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); 

} 
} 

回答

0

如果方法拋出一個異常,那麼你要麼將不得不寫拋出一個異常,或使用try/catch來處理異常的方法。在某些情況下,您必須使用try/catch,特別是如果您使用main方法調用代碼。

+0

main可以拋出一個異常就好了 –

+0

是否可以在超類的方法中使用try catch或是否需要在main方法中再次調用它? –

+0

你想在你打算處理錯誤的地方使用try/catch。這應該在調用方法中完成,而不是超類。你會想在主要方法中調用try/catch。 – BlackHatSamurai