2012-12-12 74 views
1

我不明白爲什麼我在這行收到此錯誤:未報告的異常.....必須捕獲或聲明拋出

Vehicle v = new Vehicle("Opel",10,"HTG-454"); 

,當我把這個線在try/catch,我通常不得到任何錯誤,但這次try/catch塊不起作用。

public static void main(String[] args) { 
    Vehicle v = new Vehicle("Opel",10,"HTG-454"); 

    Vector<Vehicle> vc =new Vector<Vehicle>(); 
    vc.add(v); 

    Scanner sc = new Scanner(System.in); 
    boolean test=false; 
    while(!test) 
    try { 
     String name; 
     int i = 0; 
     int say; 
     int age; 
     String ID; 

     System.out.println("Araba Adeti Giriniz..."); 
     say = Integer.parseInt(sc.nextLine()); 

     for(i = 0; i<say; i++) { 
     System.out.println("Araba markası..."); 
     name = sc.nextLine(); 

     System.out.println("araba yası..."); 
     age = Integer.parseInt(sc.nextLine()); 

     System.out.println("araba modeli..."); 
     ID = sc.nextLine(); 
     test = true; 

     vc.add(new Vehicle(name, age, ID)); 
     } 
     System.out.println(vc); 
    } catch (InvalidAgeException ex) { 
     test=false; 
     System.out.println("Hata Mesajı: " + ex.getMessage()); 
    }   
    }  
} 

這是我在Vehicle類中的構造函數;

public Vehicle(String name, int age,String ID)throws InvalidAgeException{ 
     this.name=name; 
     this.age=age; 
     this.ID=ID; 
+0

檢查如果傳遞正確的價值觀(即正確的數據類型)車輛的構造函數 - 它會幫助,如果你可以在這裏發佈構造函數定義 – Waqas

+0

「但這次try/catch塊不起作用..」向我們展示你是如何嘗試捕獲的 – Subin

+0

我也有興趣看看它是如何編譯的沒有相等數量的左/右花括號...;)(我的猜測是,你在'while(!test)'後面缺少一個'{')。 – brimborium

回答

2

它必須是這是該Vehicle構造函數聲明checked異常。在main中調用它的代碼既不聲明檢查的異常也不處理它​​,所以編譯器會抱怨它。

現在你已經張貼Vehicle構造函數中,我們可以看到,它宣稱,它拋出InvalidAgeException

public Vehicle(String name, int age,String ID)throws InvalidAgeException{ 
// here ---------------------------------------^------^ 

main不聲明它拋出InvalidAgeException,你沒有try/catch圍繞new Vehicle,所以編譯器不會編譯它。

這是檢查異常的用途:確保調用某些東西的代碼處理異常情況(try/catch)或它傳遞它的文檔(通過throws子句)。

在你的情況,你需要添加一個try/catch,你不應該有main宣佈檢查異常,如:

public static void main(String[] args) { 
    try { 
    Vehicle v = new Vehicle("Opel",10,"HTG-454"); 
    // ...as much of the other code as appropriate (usually most or all of it)... 
    } 
    catch (InvalidAgeException ex) { 
    // ...do something about it and/or report it... 
    } 
} 
+1

現貨。問題似乎與車輛構造更新,也許更新這個答案匹配。 – hyde

+0

非常感謝你,我現在明白了。 :) – mehmet

+0

@mehmet:很高興幫助! –

相關問題