抛出异常的构造函数中的 Unreachable 语句

Unreachable Statement in the constructor that throws exception

当我尝试 运行 这个程序时,我得到 unreachable statement 我尝试了不同版本的 java 但仍然无法正常工作,但我确信代码是正确的。

       // 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());
      }
   }
}

你有一个“;”在与汽车制造商的 if 结束时。

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

去掉这个“;”会好的

你用分号结束了你的 if 子句。这就是为什么投球永远达不到的原因。

if(!(make.equalsIgnoreCase("ford") ||     
   make.equalsIgnoreCase("honda") ||   
   make.equalsIgnoreCase("toyota") ||    
   make.equalsIgnoreCase("chrysler") ||    
   make.equalsIgnoreCase("other")));
        throw new Exception("Invalid make.");

虽然 Java 允许在 if 条件后只有一个动作时不使用花括号,但您应该真正习惯始终使用它们。这样可以防止你犯这样的错误。

if(!(make.equalsIgnoreCase("ford") ||    
    make.equalsIgnoreCase("honda") ||     
    make.equalsIgnoreCase("toyota") ||     
    make.equalsIgnoreCase("chrysler") ||    
    make.equalsIgnoreCase("other"))) {
       throw new Exception("Invalid make.");
}