2014-10-17 41 views
0

我不知道爲什麼我得到這個錯誤,並有一種感覺我錯過了一些明顯的東西在這裏。它發生在行上:Verify.Validate(number);錯誤:Program5.java:23:錯誤:未報告的異常異常;必須被捕獲或宣佈被拋出。任何建議,將不勝感激。異常處理編譯錯誤:異常;必須被捕獲或被宣佈爲拋出

克里斯

import java.util.Scanner; 

public class Program5 
{ 
public static void main(String[] args) 
{ 
    // The driver class should instantiate a Verify object with a range of 10 to 100. 
    Verify Verify = new Verify(10, 100); 

    //Prompt the user to input a number within the specified range. 
    System.out.print("Input a number between 10-100: "); 

    // Use a Scanner to read the user input as an int. 
    Scanner input = new Scanner(System.in); 
    int number = input.nextInt(); 

    // Use Try/Catch to test number 
    try 
    { 
     Verify.Validate(number); 
     System.out.println("Number entered: " + number); 
    } 
    catch (NumberNegativeException ex) 
    { 
     System.out.println(ex.getMessage()); 
    } 
    catch (NumberLowException ex) 
    { 
     System.out.println(ex.getMessage()); 
    } 
    catch (NumberHighException ex) 
    { 
     System.out.println(ex.getMessage()); 
    } 
}  
} 
+2

解決方法是在錯誤消息 – Reimeus 2014-10-17 16:49:53

+1

是,無論是「catch(Exception)」還是讓主方法拋出異常 – spiderman 2014-10-17 16:51:48

+0

這必須是大約1000倍以上的愚蠢。 – 2014-10-17 17:02:48

回答

1

按照您的代碼有3種類型的例外的你的驗證(int)方法可以拋出:

1)NumberHighExc主器件接收

2)NumberLowException

3)NumberNegativeException

因此,對於你的validate(INT)代碼方法可能如下:

public void validate(int number) throws NumberHighException, NumberLowException, 
            NumberNegativeException { 
    if(number > 100) 
     throw new NumberHighException("Number is High"); 
    if(number < 10) 
     throw new NumberLowException("Number is Low"); 
    if(number < 0) 
     throw new NumberNegativeException("Number is Negative"); 
    else 
     System.out.println("Your Entered Number is valid"); 
} 

現在,在編譯代碼,你得到錯誤在:

catch (NumberNegativeException ex) // Line no 23, where you are getting the error 
{ 
    System.out.println(ex.getMessage()); 
} 

並且所產生的誤差是:

error: unreported exception Exception; must be caught or declared to be thrown 

這表明拋出的異常是更高(超類)的鍵入不是作爲與catch塊指定。

所以,在某處你的validate()方法,你扔類型異常的異常。只要糾正它,你會沒事的。

-1

讓我們嘗試使用更普遍的難題: 嘗試{ .... }趕上(例外五){} 這樣,你因爲每個捕獲所有的錯誤錯誤擴展類錯誤

相關問題