Reputation: 11
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;
Upvotes: 1
Views: 262
Reputation: 1074208
It must be It's that the Vehicle
constructor declares a checked exception. Your code calling it in main
neither declares that checked exception nor handles it, so the compiler complains about it.
Now that you've posted the Vehicle
constructor, we can see that it declares that it throws InvalidAgeException
:
public Vehicle(String name, int age,String ID )throws InvalidAgeException{
// here ---------------------------------------^------^
Your main
doesn't declare that it throws InvalidAgeException
, and you don't have a try/catch
around the new 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 a throws
clause).
In your case, you'll need to add a try/catch
as you shouldn't have main
declaring checked exceptions, e.g.:
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...
}
}
Upvotes: 2