如何修改此代码以获取异常错误?

时间:2016-03-31 22:00:06

标签: java oop exception nullpointerexception try-catch

我的目标是修改我的setter以在传递无效值时抛出tractorException然后修改我的main方法以尝试捕获异常。问题是我不知道如何修改我的setter以产生异常错误。请帮助。

import java.util.*;

public class tractorException
{
      protected String name;
      protected int VehicleID; 

     public String setName(String name) 
       {
           return this.name = name;

       }

       String getName() 
       {
           return this.name;        
       }

     public int setVehicleID(int VehicleID)
       {
           if (VehicleID <= 0 || VehicleID > 100000) 
           {
             return -1;
           } 
           else 
           {
              this.VehicleID = VehicleID;
              return VehicleID;

           }
        }

          public int getVehicleID()
        {
            return this.VehicleID;
        }

      tractorException()
      {
         setVehicleID(0);
         setName("");
      }

  @Override
    public String toString() 
    {
        return "Tractor Name= " + name + "VIN= " + VehicleID;

    }
   public static void main (String[] args)
   {

    }
}

1 个答案:

答案 0 :(得分:1)

尝试做:

public class TractorException extends Exception
{
    //implement whatever methods are necessary
}

在代表Tractor

的班级中
public int setVehicleID(int VehicleID) throws TractorException
{
   if (VechicleID <= 0) {
     throw new TractorException("Invalid VIN: " + VehicleID);
   }
   else {
     this.VehicleID = VehicleID;
     return this.VehicleID;
   }

}

在main方法中,捕获TractorException