User interface 调用方法,该方法根据执行的操作创建文件
我正在尝试调用创建文件的方法,但是我正在从执行的操作调用该方法,该操作根本无法引发IOException 代码如下:User interface 调用方法,该方法根据执行的操作创建文件,user-interface,try-catch,ioexception,throw,User Interface,Try Catch,Ioexception,Throw,我正在尝试调用创建文件的方法,但是我正在从执行的操作调用该方法,该操作根本无法引发IOException 代码如下: /* ACTION PERFORMED**/ public void actionPerformed(ActionEvent evt){ Object source = evt.getSource(); if (source == add) { String mothername = " "; String fatherna
/* 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();
}
//错误在两条蓝线中,显示的错误为:
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
请告诉我要更改什么答案在错误消息中:您必须处理您的异常。他们不只是为了在事情发生轻微倾斜时把事情搞砸——他们是为了让你知道当错误发生时你想如何处理错误。这意味着您必须考虑程序的哪些部分将处理错误条件,以及程序的哪些部分将假定错误不会发生 您可能希望actionPerformed方法在屏幕上放置一个错误对话框,提醒用户“保存”按钮实际上丢弃了他们所有的工作。在这种情况下,将所有对writeToFile的调用封装在try/catch块中,并进行适当的处理 您可能希望writeToFile将一条消息记录到记录应用程序的log4j实例,或者在写入失败时简单地向标准错误或标准输出一些内容。在这种情况下,undelcare会从writeToFile中抛出IOException,将方法的内容包装在try/catch块中并进行适当的处理
至少在我的经验中,处理错误是大多数应用程序的大部分代码。遗憾的是,学校没有把它教得更好,但这是你学习设计权衡的机会,你可以在这里尝试我的两个建议,并注意到课程中其他地方的影响。这与你的第一个问题a一样糟糕,b相同,在这个例子中我需要抓住什么?