[英]Struggling with exceptions, try/catch block and singleton in Java
我正在尝试学习在Java中处理错误/抛出异常。 我有一个类UserDatabase,它保存着一个学生集合,它也应该将集合保存到文件中。
我相当确定自己做得不好的是文件处理方法。 方法public boolean saveDatabase不应引发异常,而应在try-catch中进行处理,并应使用Student类中Student对象上的student类的encode方法将每个对象写为文件中的一行。 这个正在编译中,但是在我看来。 在书中说写方法public boolean saveDatabase(); 如您所见,我更改了标题以使其对我有意义。 这主要是因为我不知道如何编写以()结尾的标题的方法。
方法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
因为您一开始就不需要它,也从未分配任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.