2017-12-03 19 views
0

Java에서 오류 처리/예외 처리에 대한 작업을 배우려고합니다. 나는 학생 컬렉션을 가지고있는 클래스 인 UserDatabase를 가지고 있으며, 콜렉션을 파일에 저장해야한다.Java에서 예외/try catch/블록 및 싱글 톤 문제가 발생했습니다.

필자가 올바르게하지 않은 것은 파일 처리 방법입니다. 메서드 public boolean saveDatabase는 예외를 throw하고 try-catch에서 처리해야하며 Student 객체의 student 클래스에서 encode 메서드를 사용하여 모든 객체를 파일의 한 줄로 작성해야합니다. 이것은 컴파일하는 것이지만 그것은 내게 떨어져 보인다. 책에서 그것은 메소드를 작성하는 것을 말한다 public boolean saveDatabase(); 당신이 볼 수 있듯이, 나는 그것에 대한 헤더를 바꾸어서 나에게 의미가있다. 이것은 주로()로 끝나는 헤더를 가진 메소드를 작성하는 방법을 모른다.

메서드 public boolean loadDatabase는 가능한 IO 오류도 처리하고 오류가 발생하면 false를 반환해야합니다. 필드의 모든 행에 대해 sudent 클래스의 public Student (String encodedStudent) 생성자에 의해 student 객체를 만들어야합니다. 파일의 한 줄을 학생으로 디코딩 할 수없는 경우 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"); 
     } 
    } 

답변

0

귀하의 코드가

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

간단히 예외 발생 여부 어떠했는지에 따라 true/false을 반환해야한다 :

여기 내 코드입니다. 더 이상 필요 없으므로 saved을 버리십시오. encode은 처음에는 필요 없으며 값을 할당하지 않았으므로 삭제하십시오.

+0

대단히 감사합니다! 코드가 오류없이 컴파일됩니다. 하지만이 작업에서는 학생 개체에 encode 메서드를 사용하고 모든 개체를 파일의 한 줄로 작성한다고 명시되어 있습니다. UserDatabase 클래스는 Students 컬렉션을 보유하고 있으며 컬렉션을 파일에 저장할 수도 있습니다. 이 작업을 어떻게 성공적으로 수행 할 수 있습니까? – Angelica

+0

@Angelica 나는 그런 것을 알았다. 이제 "일"입니다. 주석을 추가 한'try' 블록 안의 모든 작업을 수행해야합니다. "userdatabase"또는 액세스 권한이있는 "encode"메소드를 알지 못합니다. 그리고 나는 정말로 그들에 대해 알고 싶지 않습니다. 방금 try-catch를 사용하는 방법과 반환 할 위치에 대한 일반적인 아이디어를 제공해 드리고자합니다. – luk2302

+0

알겠습니다. 이해합니다. 하지만 고마워요. 이제 나에게 더 의미가 있습니다! – Angelica