2012-12-12 75 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:很高兴帮助! –

相关问题