gpt4 book ai didi

java - 在Java中尝试异常,try/catch block 和单例

转载 作者:行者123 更新时间:2023-12-03 08:48:36 24 4
gpt4 key购买 nike

我正在尝试学习在Java中处理错误/抛出异常。
我有一个类UserDatabase,它保存着一个学生集合,它也应该将集合保存到文件中。

我相当确定自己做得不好的是文件处理方法。方法public boolean saveDatabase不应引发异常,并且应在try-catch中进行处理,并应使用Student类中Student对象上的student类的encode方法将每个对象写为文件中的一行。这是正在编译,但在我看来。在书中说写方法public boolean saveDatabase();如您所见,我更改了标题以使其对我有意义。这主要是因为我不知道如何编写以()结尾的 header 的方法;

方法public boolean loadDatabase也应该处理可能的IO错误,如果发生错误则返回false。对于该字段中的每一行,它应该由sudent类的构造函数public Student(String encodingStudent)创建一个学生对象。如果无法将文件中的一行解码为学生,则应抛出新的异常DatabaseFormatException(这是一个单独的类)。这个也被列为public boolean loadDatabase();在书里。面对现实吧,这个完全关闭了。我不知道该怎么办,而且我已经花了好几个小时不停地工作,看书,上网阅读,我迷路了。

这是我的代码:

   /**
* This method should not throw exceptions.
* By using a try/catch block, we anticipate possible failures.
* We recognize that these actions might fail and throw errors.
*/
public boolean saveDatabase() throws IOException {
//This method is using the encode method on student objects and should
//write each object as a line in the file.
String encode = null;
boolean saved;
try {

encode = null;
userdatabase.saveDatabase();
saved = false;
}
catch (IOException e) {
System.out.println("Error");
saved = false;
}
finally {
if(encode.equals(students)) {
//System.out.println("Students" + students)?;
saved = true;
}
}
return saved;
}

/**
* Method loadDatabase should handle possible IO errors, and return false
* if one occurs. Otherwise, it should return true and create a new
Student object
* by using the constructor public Student(String encodedStudent).
* If a line cannot be decoded as a student, the method should throw a
new
* exception "DatabaseFormatException".
*
*/
public boolean loadDatabase() throws IOException,DatabaseFormatException {
//Attempting to use the String encodedStudent constructor from Student class
String encodedStudent = null;
boolean loaded;
try {
//Attempting to create possible IO errors returning false if they occur
enco dedStudent = null;
//UserDatabase.loadDatabase(encodedStudent);
loaded = false;
}
catch(IOException e) {
if (encodedStudent == null) {
System.out.println("Error");
loaded = false;
}
}
//Trying a for each loop to throw a DatabaseFormatException

for(Student student : students) {
//This is supposed to throw a DatabaseFormatException if a
//line in the file cannot be decoded as a student!
if(student.getName.isEmpty() && this.course.isEmpty()) {
throw new DatabaseFormatException(
"No student found");
}
}

最佳答案

您的代码应为

public boolean saveDatabase() {
try {
// maybe do some more work...
userdatabase.saveDatabase();
return true;
} catch (IOException e) {
return false;
}
}

只需根据是否发生异常返回 true/false。删除 saved,因为您不再需要它。删除 encode,因为您一开始就不需要它,也从未为其分配值。

关于java - 在Java中尝试异常,try/catch block 和单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47618666/

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