java - 调用方法时出现 IOException 错误

标签 java exception file-io

我正在尝试写入文件。

我已经在 writeHtmlFile 方法中声明了异常,但是当我尝试调用 writeHtmlFile 方法时,错误“必须捕获或声明抛出未报告的异常 java.io.IOException”仍然出现?

public class PartB extends ChangeDrawer
{

  public static ChangeDrawer cd = new ChangeDrawer();
  static int[] floatDrawer = {8,5,4,4,5,20,20,6,10,3,8};

   {
      String selection="";
      Scanner scan = new Scanner (System.in); 

      System.out.println ("Enter P to make a purchase and receive your change");
      System.out.println ("Enter L to load the Change drawer");
      System.out.println ("Enter H to write the contents of the Change Drawer to a web page");
      System.out.println ("Enter E to exit the program");


    while (selection.compareTo("E")!=0)
    {
      selection = scan.next();
      if (selection.compareTo("P")== 0)
         makeChange();
      else if (selection.compareTo("L")==0)
         loadFloat();
       else if (selection.compareTo("H")==0)
         writeHtmlFile(); //unreported exception java.io.IOException must be caught or
                          //declared to be thrown


    }
        System.out.println ("Ending .............................. ");
    }


    //more code exists between these two sets

   public static void writeHtmlFile() throws IOException
   {
    FileWriter fwriter = new FileWriter("ChangeDrawer.html");
    PrintWriter outputFile = new PrintWriter(fwriter);
    outputFile.println("This should work!");

  }

最佳答案

调用 writeHtmlFile 的代码必须捕获(或重新声明抛出)IOException。由于调用代码位于静态初始化程序中,因此它必须是前者。

关于java - 调用方法时出现 IOException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11662048/

相关文章:

file-io - 为什么Hadoop文件系统不支持随机I/O?

c - 需要帮助修复在文本文件中查找 max_min_numbers 的函数

java - 有没有办法在 hibernate 中选择额外的字段(不保存)?

java - RCP SWT Eclipse - 清除复合容器

java - RxJava 没有重复的合并

java - 开关中的异常处理

JavaMail 一段时间后停止发送邮件

python - 单行异常处理

java - 使用可注入(inject)单例

matlab - MATLAB 中的 .m 和 .mat 文件有什么区别