Search code examples
javatry-catchthrow

Unreachable Statement in the constructor that throws exception


When I try to run this program I am getting unreachable statement I tried different versions of java and still not working but I am sure that the code is right.

       // Lec 25b
public class UsedCar{
   private int VIN;
   private String make;
   private int year;
   private int milage;
   private int price;
   
   public UsedCar(int VIN, String make, int year, int milage, int price) throws Exception{
      if(VIN<1000 || VIN>9999)
         throw new Exception("VIN is not four digits.");
      this.VIN = VIN;
      if(!(make.equalsIgnoreCase("ford") || make.equalsIgnoreCase("honda") || make.equalsIgnoreCase("toyota") || make.equalsIgnoreCase("chrysler") || make.equalsIgnoreCase("other")));
      throw new Exception("Invalid make.");
      this.make = make;
      if(year<=1997 || year>=2017)
         throw new Exception("Year is not betwean 1997 and 2017.");
      this.year = year;
      if(milage<0)
         throw new Exception("Milage is negative.");
      this.milage = milage;
      if(price<0)
         throw new Exception("Price is negative.");
      this.price = price;
   }
   public static void main(String[] args){
      try{
         UsedCar car = new UsedCar(1234,"ford",1999,152,25000);
      }
      catch(Exception exp){
         System.out.println(exp.getMessage());
      }
   }
}

Solution

  • You have a ";" at the end of the if with the car manufacturer.

    if(!(make.equalsIgnoreCase("ford") || make.equalsIgnoreCase("honda") || make.equalsIgnoreCase("toyota") || make.equalsIgnoreCase("chrysler") || make.equalsIgnoreCase("other")));
    

    Remove this ";" and it will be OK