1.想在捕获一个异常后抛出另一个异常,并且希望把始的异常信息保存下来,这种叫做异常链
2.在throwable的子类中,只有3种异常类提供了cause参数 Error,Exception,RuntimeException
3.如果要把其它异常连接起来,应该用initCause()而不是构造器
class DynamicFieldsException extends Exception{
}
public class DynamicFields {
private Object[][] fields;
public DynamicFields(int initialSize) {
fields = new Object[initialSize][2];
for(int i = 0;i < initialSize;i++) {
fields[i] = new Object[] {null,null};
}
}
public String toString() {
StringBuilder result = new StringBuilder();
for (Object[] objects : fields) {
result.append(objects[0]);
result.append(" :");
result.append(objects[1]);
result.append("\n");
}
return result.toString();
}
private int hasField(String id) {
for(int i = 0;i <fields.length;i++) {
if(id.equals(fields[i][0]))
return i;
}
return -1;
}
/**
*
* @param id
* @return
* @throws NoSuchFieldException
*/
private int getFieldNumber(String id) throws NoSuchFieldException{
int fieldNum = hasField(id);
if(fieldNum == -1)
throw new NoSuchFieldException();
return fieldNum;
}
private int makeField(String id) {
for(int i = 0; i < fields.length;i++)
if(fields[i][0] == null) {
fields[i][0] = id;
return i;
}
Object[][] tmp = new Object[fields.length + 1][2];
System.arraycopy(fields, 0, tmp, 0,fields.length);
tmp[tmp.length - 1] = new Object[] {null,null};
fields = tmp;
return makeField(id);
}
public Object getField(String id) throws NoSuchFieldException{
return fields[getFieldNumber(id)][1];
}
public Object setField(String id,Object value) throws DynamicFieldsException{
if(value == null) {
DynamicFieldsException dfe = new DynamicFieldsException();
dfe.initCause(new NullPointerException());
throw dfe;
}
int fieldNumber = hasField(id);
if(fieldNumber == -1)
fieldNumber = makeField(id);
Object result = null;
try {
result = getField(id);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
fields[fieldNumber][1] = value;
return result;
}
public static void main(String[] args) {
DynamicFields df = new DynamicFields(3);
System.out.println(df);
try {
df.setField("d", "A value for d");
df.setField("number", 47);
df.setField("number2", 48);
System.out.println(df);
df.setField("number3", 11);
System.out.println("df" + df);
System.out.println("df.getField(\"d\"):" + df.getField("d"));
Object field = df.setField("d", null);
} catch (NoSuchFieldException e) {
e.printStackTrace(System.err);
} catch (DynamicFieldsException e) {
e.printStackTrace(System.err);
}
}
}
结果为:
null :null
null :null
null :null
d :A value for d
number :47
number2 :48
dfd :A value for d
number :47
number2 :48
number3 :11
df.getField("d"):A value for d
com.yaoqiang._class.DynamicFieldsException
at com.yaoqiang._class.DynamicFields.setField(DynamicFields.java:65)
at com.yaoqiang._class.DynamicFields.main(DynamicFields.java:97)
Caused by: java.lang.NullPointerException
at com.yaoqiang._class.DynamicFields.setField(DynamicFields.java:66)
... 1 more