【发布时间】:2020-02-28 13:49:27
【问题描述】:
我在 Test1 类中抛出自定义异常并将列表传递给构造函数:
public class Test1 {
public List<Journal> method1(String str) throws SectionNotFoundException {
List<Journal> list = new ArrayList<>();
//...
else if(...) {
throw new SectionNotFoundException(list);
}
//...
}
}
它让我回到我在 Test1 类内调用 method1 的行 Test2 就像:
public class Test2 {
//...
public void method() {
//...
Test1 test1 = new Test1();
try {
list = test1.method1(text);
} catch (SectionNotFoundException e) {
//...
}
}
}
在名为SectionNotFoundException 的自定义异常中,我想获取空列表而不是null:
public class SectionNotFoundException extends Throwable {
List<Journal> journalList;
public SectionNotFoundException(List<Journal> journalList) {
this.journalList = journalList;
emptyArrayList();
}
public ArrayList<Object> emptyArrayList() {
return new ArrayList<>();
}
}
但真正的问题是,如果emptyList的返回值从未被使用过,如何正确写入。
【问题讨论】:
-
使用异常来抽象一些值并不是一个好习惯,比如这里的
List<Journal> journalList。您可以在捕获异常的地方分配一个空列表。 -
@invzbl3 通过将一个空列表传递给您的构造函数?
-
@Stultuske 如果我的列表返回
null,我会抛出异常,但我正在尝试在自定义异常类中更改它,如您所见我的问题。跨度> -
@inzvbl,不,你会一直覆盖它。尝试(在您的构造函数中)类似: this.journalList = journalList == null ?新的 ArrayList() : journalList;
-
现在说得通了。感谢您指出,我会测试并纠正它。