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

Java 如何修改此代码以获得异常错误?,java,oop,exception,nullpointerexception,try-catch,Java,Oop,Exception,Nullpointerexception,Try Catch,我的目标是修改setter,以便在传入无效值时抛出tractorException,然后修改main方法以尝试捕获异常。问题是我不知道如何修改我的设置程序以产生异常错误。请帮忙 import java.util.*; public class tractorException { protected String name; protected int VehicleID; public String setName(String name)

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

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)
   {

    }
}
试着做:

public class TractorException extends Exception
{
    //implement whatever methods are necessary
}
在表示拖拉机的类中


在main方法中,catch TractorException

您的代码没有多大意义-首先,TractorException应该是Exception或RuntimeException的子类。其次,您可能不希望所有代码都进入TractorException。看一看a是一个好的开始。谢谢,我现在懂了一点。
public int setVehicleID(int VehicleID) throws TractorException
{
   if (VechicleID <= 0) {
     throw new TractorException("Invalid VIN: " + VehicleID);
   }
   else {
     this.VehicleID = VehicleID;
     return this.VehicleID;
   }

}