gpt4 book ai didi

java - 捕获 NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 06:55:16 33 4
gpt4 key购买 nike

下面是别人写的类。

我面临的问题是,当它进入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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com