调用方法时出现IOException错误

时间:2012-07-26 03:44:59

标签: 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!");

  }

1 个答案:

答案 0 :(得分:2)

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