我正在尝试学习与Java中的错误处理/投掷异常一起工作。我有一个课程,用户数据库,拿着一系列学生,还应将收集保存到文件中。
我相当确定我还没有正确完成的是文件处理方法。方法public boolean savedatabase不应抛出异常,而应在尝试键入中处理,并使用学生类上的"学生"类的编码方法将每个对象写入文件中的一行。这是在编译,但看上去对我来说。在书中,它说写了公共布尔savedatabase()的方法;如您所见,我更改了标头,以使其对我有意义。这,主要是因为我不知道如何用标头以()结尾;
编写方法方法公共布尔负载数据库还应处理可能的IO错误,并在发生错误时返回false。对于字段中的每一行,它都应由Supent类的构造函数公共学生(字符串编码)创建一个学生对象。如果文件中的一行无法解码为学生,则应抛出新的异常,数据库FormateXception(这是单独的类)。这也列为公共布尔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
,因为您首先不需要它,也从未为其分配一个值。