我的目标是,如果传入无效值,则修改我的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)
{
}
}
尝试做:
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;
}
}
在您的主要方法中,捕获TractorException
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句