【发布时间】:2018-03-25 18:57:16
【问题描述】:
我有一个类 X 将 ints 保存在一个数组中:
public class X{
public int[] a;
public boolean[] allocated;
//constructor
public X(int len){
this.a = new a[len];
this.a = new allocated[len];
}
public void save(int tosave) throws ArrayStoreException{
int pos = 0;
for(int i=0; i<allocated.length; i++){
if(allocated[i] == true){
pos++;
}
}
if(pos == allocated.length){
throw new ArrayStoreExeption("no free space left");
}
a[pos] = tosave;
allocated[pos] = true;
}
}
还有我仍然需要实现的 Y 和 save2 类...
public class Y extends X{
public void save2(int tosave){
// to be implemented
}
}
对于save2,我希望它与save 执行相同的操作,但如果没有剩余可用空间或发生 ArrayStoreException,那么我希望数组的大小加倍,然后插入参数到数组。
如果我这样做:
try{
super.save(tosave); // If no exception is thrown, does it save 'tosave'?
}catch(ArrayStoreExeption e){
System.out.println("noe free sapce left");
}
我的第一个问题是:如果try块没有触发异常,catch块之后的代码会执行吗?
如果没有更多空间或抛出异常,我不知道将这段代码保存在哪里,这会使数组大小加倍。
有人可以帮忙吗?
编辑: 我可以在 catch 块内放置使数组加倍的代码吗?
【问题讨论】:
-
catch 只会在 try 块抛出 ArrayStoreException 时执行。如果您希望您的代码始终执行,您可以使用 finally docs.oracle.com/javase/tutorial/essential/exceptions/…
-
我只希望在抛出异常时执行一段特定的代码,否则我希望它在 try 块内执行操作
标签: java arrays inheritance exception