下面是别人写的类。
我面临的问题是,当它进入null as the rawString的parse method时,它抛出了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;
}
}发布于 2012-11-13 10:56:22
你需要做四件事:
我得到的印象可能是不公平的,您直接跳到了步骤4,而没有考虑可能的原因和适当的问题报告。
发布于 2012-11-13 10:46:04
您可以添加一个带有如下条件的提前退出:
if (rawString != null) {
return attr; // or other value you prefer
}您还可以确保parse方法的调用方测试null值,并避免在空值时调用parse。
发布于 2012-11-13 10:49:53
这取决于应用程序中对空值的容忍度。如果您希望用户不将空字符串传递给parse()方法,那么您应该进行防御性的null检查并抛出异常。
if (null == rawString) {
throw new CustomException("rawString cannot be null");
}这同样适用于NumberFormatException的catch块,您应该抛出一个带有适当消息的异常,而不是默默地将Byte属性的值设置为null。
但是,如果null是完全可接受的,那么您应该执行防御性的null检查,并将Byte属性设置为null。NumberFormatException当然不应该被抑制,IMHO。
https://stackoverflow.com/questions/13354875
复制相似问题