下面是别人写的类。
我面临的问题是,当它进入parse method
时与 null as the rawString
,它正在扔NumberFormatException
。
所以我想做的是,我应该捕获 NumberFormatException 和 set the value itself as null
。那么我的做法是对的吗?
public class ByteAttr {
@JExType(sequence = 1)
private Byte value;
public static ByteAttr parse(String rawString) {
ByteAttr attr = new ByteAttr();
try {
attr.setValue(Byte.valueOf(rawString));
} catch (NumberFormatException nfEx) {
attr.setValue(null);
}
return attr;
}
public Byte getValue() {
return this.value;
}
public void setValue(Byte value) {
this.value = value;
}
}
最佳答案
正确的方法取决于您想要在程序中完成的任务。
- 如果
ByteAttr.getValue()
在程序中稍后返回null
有意义,那么您的方法就可行。 - 但是,您需要考虑如果使用无法解读的参数(包括
null
)调用parse
,您是否应该抛出异常。另一种方法是捕获NumberFormatException
并抛出一个在程序中具有语义含义的不同异常。
public static ByteAttr parse(String rawString) throws BadAttributeException { ByteAttr attr = new ByteAttr(); try { attr.setValue(Byte.valueOf(rawString)); } catch (NumberFormatException nfEx) { throw new BadAttributeException(nfEx); // wrap original exception } return attr; }
- 另一种技术是在
rawString
无法破译的情况下将默认值传递给parse
:
public static ByteAttr parse(String rawString, Byte defaultValue) { ByteAttr attr = new ByteAttr(); try { attr.setValue(Byte.valueOf(rawString)); } catch (NumberFormatException nfEx) { attr.setValue(default); } return attr; }
关于java - 捕获 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354875/