java null 手动异常处理
java null manual exception handling
我有 class 平面的这个静态方法,其中 returns 来自某个 int id 的对象:
private static ArrayList<Plane>Planes = new ArrayList<Plane>();
public static Plane getPlane(int id)
{
Plane p = null;
int i=0;
while(i<=Planes.size())
{
if(Planes.get(i).getid()==id)
{
p = Planes.get(i);
break;
}
i++;
}`
return p;
}
我有这段代码,当 Plane 对象为 null 并且打印 Plane 不存在时,我想手动抛出异常!:
try
{
Plane planetofly = Plane.getPlane(pid);
if(planetofly==null)
{
throw new Exception("Plane doesnt exist!");
}
this.planetofly = planetofly;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
但是当具有该 ID 的平面不存在时,我没有得到“输出中不存在平面”,而是从 IndexOutofBounds 输出消息 Exception.What 我做错了吗?
索引越界意味着您正在尝试访问数组中不存在的索引。
这一行就是问题所在。
while(i<=Planes.size())
索引从零开始到大小 - 1 结束,因此您必须检查是否小于、不小于或等于。像这样:
while(i < Planes.size())
我有 class 平面的这个静态方法,其中 returns 来自某个 int id 的对象:
private static ArrayList<Plane>Planes = new ArrayList<Plane>();
public static Plane getPlane(int id)
{
Plane p = null;
int i=0;
while(i<=Planes.size())
{
if(Planes.get(i).getid()==id)
{
p = Planes.get(i);
break;
}
i++;
}`
return p;
}
我有这段代码,当 Plane 对象为 null 并且打印 Plane 不存在时,我想手动抛出异常!:
try
{
Plane planetofly = Plane.getPlane(pid);
if(planetofly==null)
{
throw new Exception("Plane doesnt exist!");
}
this.planetofly = planetofly;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
但是当具有该 ID 的平面不存在时,我没有得到“输出中不存在平面”,而是从 IndexOutofBounds 输出消息 Exception.What 我做错了吗?
索引越界意味着您正在尝试访问数组中不存在的索引。
这一行就是问题所在。
while(i<=Planes.size())
索引从零开始到大小 - 1 结束,因此您必须检查是否小于、不小于或等于。像这样:
while(i < Planes.size())