未报告的异常.....必须被捕获或声明被抛出

时间:2012-12-12 08:44:25

标签: java try-catch netbeans-7

我不明白为什么我会在这一行收到此错误:

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

当我将这一行放在try/catch中时,我通常不会收到任何错误,但这次尝试/ 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;

1 个答案:

答案 0 :(得分:2)

必须是 Vehicle构造函数声明了一个已检查的异常。您在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...
  }
}
相关问题