gpt4 book ai didi

java - 如何处理要传播给调用者的异常?

转载 作者:行者123 更新时间:2023-12-01 16:47:29 25 4
gpt4 key购买 nike

我是一名正在转向 Java/Scala 的 Pythonista,我想知道如何处理您希望在发生异常时抛出异常的情况。以下面的玩具为例:

public class PersonSaver {
private final File file;

public PersonSaver(File file) {
this.file = file;
}

public void save(List<Person> people) {
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
output.writeObject(people);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

在Python中,如果找不到文件,我希望它抛出一个错误,并让调用代码处理异常。惯例只是重新抛出相同的异常吗?

最佳答案

您可以让您的方法抛出这些异常:

public class PersonSaver {
private final File file;

public PersonSaver(File file) {
this.file = file;
}

public void save(List<Person> people) throws FileNotFoundException {
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
output.writeObject(people);
} catch (IOException e) {
//handle the exception you want to handle
e.printStackTrace();
}
}
}

只需确保使用 throws 语句声明您的方法,否则您的编译器可能不喜欢它;)

您也可以采用这种方式(我们称之为半异常处理):

public class PersonSaver {
private final File file;

public PersonSaver(File file) {
this.file = file;
}

public void save(List<Person> people) throws FileNotFoundException, IOException {
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
output.writeObject(people);
} catch (IOException e) {
/*Some code to clear some data or to handle the
exception but still throw an exception higher*/
throw e;
}
}
}

关于java - 如何处理要传播给调用者的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293141/

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