I dont understand why I am getting this error at this line:
Vehicle v = new Vehicle("Opel",10,"HTG-454");
when I put this line in a try/catch, I usually dont get any error but this time try/catch block doesn’t work.
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());
}
}
}
and this is my constuctor in Vehicle class;
public Vehicle(String name, int age,String ID )throws InvalidAgeException{
this.name=name;
this.age=age;
this.ID=ID;
It must beIt’s that theVehicleconstructor declares a checked exception. Your code calling it inmainneither declares that checked exception nor handles it, so the compiler complains about it.Now that you’ve posted the
Vehicleconstructor, we can see that it declares that it throwsInvalidAgeException:Your
maindoesn’t declare that it throwsInvalidAgeException, and you don’t have atry/catcharound thenew Vehicle, so the compiler won’t compile it.This is what checked exceptions are for: Ensuring that the code calling something either handles the exceptional condition (
try/catch) or documents that it passes it on (via athrowsclause).In your case, you’ll need to add a
try/catchas you shouldn’t havemaindeclaring checked exceptions, e.g.: