Exception 异常处理和构造函数

Exception 异常处理和构造函数,exception,file-io,constructor,Exception,File Io,Constructor,我正在将数据写入文件,当我写入此数据时,我希望这样做,以便如果文件未打开,它将向用户发送一条消息,说明出现了问题。我这样做的方法是调用方法进行写入,如果失败,它将返回false。这样我可以提示用户做一些事情来检查发生了什么 然而,当我创建对象时,我不能从构造函数返回任何东西,所以我有点困惑我应该怎么做 public class Writetofile { BufferedWriter writer = null; public Writetofile(String[]details) thro

我正在将数据写入文件,当我写入此数据时,我希望这样做,以便如果文件未打开,它将向用户发送一条消息,说明出现了问题。我这样做的方法是调用方法进行写入,如果失败,它将返回false。这样我可以提示用户做一些事情来检查发生了什么

然而,当我创建对象时,我不能从构造函数返回任何东西,所以我有点困惑我应该怎么做

public class Writetofile {
BufferedWriter writer = null;

public Writetofile(String[]details) throws IOException{
String machine= details[0];
String date=details[1];
String start_time = details[2];     
try{
   File new_cal= new File("C:\\Activity_Calibrator\\log\\"+machine+"\\"+machine+date+".txt");
   new_cal.getParentFile().mkdir();
   FileWriter fwriter = new FileWriter(new_cal);
   writer = new BufferedWriter(fwriter); 
   writer.write("Linear Calibratiton for " + machine + " carried out " + date+" ./n");
   writer.close();
  }
catch(Exception e){ in here I would like to be able to send a message back to m
code so that it can tell the user to check the folder etc}
} 
当我调用记录数据时,如果出现问题,它将向调用类返回false。我可以留言

 public boolean recordData(String record) throws IOException{
try{
    writer.append(record);
    writer.close();
    return true;
   }
catch(Exception e){
    return false;

   }
 }
 }
 } 

构造函数不应该做任何事情。构造函数是与对象分配密切相关的初始化阶段

要避免抛出异常,或在构造函数中执行任何可能抛出异常的操作

Java没有将分配和初始化阶段分开,构造函数中不应包含任何代码,尤其是IO代码