0

ファイルを作成するメソッドを呼び出そうとしていますが、実行されたアクションからそのメソッドを呼び出していますが、IOException をスローすることはできません...

コードは次のとおりです。

/* ACTION PERFORMED**/
public void actionPerformed(ActionEvent evt){
    Object source = evt.getSource();
    if (source == add)
    {
        String mothername = " ";
        String fathername = " ";
        String motherphone = " ";
        String fatherphone = " ";

        Patient patient = new Patient(...));

        printPatients(patient);

        System.out.println("past printing patient");

        writetoFile(patient); //giving an error
    }

    if (source == uadd)
    {
        Patient patient = new Patient(...));

        printPatients(patient);

        writetoFile(patient); //giving an error
    }
}

//This is the method I am trying to call

public static void writetoFile(Patient p) throws IOException
{
    RandomAccessFile inout = new RandomAccessFile("PatientsInfo.dat", "rw");

    inout.seek(inout.length());
    inout.writeUTF(p.getName());
    inout.writeUTF(p.getAge());
    inout.writeUTF(p.getGender());
    inout.writeUTF(p.getSiblings());
    inout.writeUTF(p.getID());
    inout.writeUTF(p.getNationality());
    inout.writeUTF(p.getCivilStatus());
    inout.writeUTF(p.getProfession());
    inout.writeUTF(p.getPhone1());
    inout.writeUTF(p.getPhone2());
    inout.writeUTF(p.getEmail());
    inout.writeUTF(p.getMotherName());
    inout.writeUTF(p.getFatherName());
    inout.writeUTF(p.getMotherPhone());
    inout.writeUTF(p.getFatherPhone());
    inout.writeUTF(p.getMedication());
    inout.writeUTF(p.getDoctorsName());
    inout.writeUTF(p.getFrequency());
    inout.writeUTF(p.getPrice());
    System.out.println("names and sentinel value sent to file Countries.dat");

    inout.close();
}

// エラーは 2 本の青い線にあり、表示されるエラーは次のとおりです。

Error: C:\Users\Pedro Quintas\Documents\Documents and Work
\Escola\Computer Science\Programs\Dossier\AddPatient.java:362:
unreported exception java.io.IOException; must be caught or
declared to be thrown

何を変えるか教えてください

4

1 に答える 1

0

答えはエラー メッセージにあります:) 例外を処理する必要があります。それらは、物事がわずかに斜めになったときに物事を爆破するためだけに存在するのではありません。エラーが発生したときに、エラーをどのように処理したいかを理解するために存在します。つまり、プログラムのどの部分でエラー条件を処理するか、プログラムのどの部分でエラーが発生しないと想定するかを考える必要があります

actionPerformed()メソッドでエラー ダイアログ ボックスを画面に表示して、「保存」ボタンが実際にすべての作業を破棄したことをユーザーに警告することができます。その場合、これらすべての呼び出しをwriteToFile()try/catch ブロックでラップし、適切に処理します。

writeToFile()アプリケーションのログを記録するlog4jインスタンスにメッセージを記録したり、書き込みが失敗したときに標準エラーまたは標準出力に何かを吐き出したりすることができます。その場合、あなたのthrows IOExceptionからundelcare しwriteToFile()、メソッドの内容を try/catch ブロックでラップし、適切に処理します。

エラー処理は、少なくとも私の経験では、ほとんどのアプリケーションのコードの大部分を占めています。残念なことに、学校がそれをより適切に教えていませんが、ここで私の提案の両方を試し、プログラムの他の場所での影響に気付くことで、デザインのトレードオフが何であるかを学ぶ機会がここにあります.

于 2011-01-21T13:37:39.540 に答える