【问题标题】:When calling a method IOException Error appears调用方法时出现IOException错误
【发布时间】:2012-07-26 03:44:58
【问题描述】:

我正在尝试写入文件。

我已经在 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!");

  }

【问题讨论】:

  • 您是否导入了正确的 IOException?
  • 好的。阅读下面基思兰德尔的回答,我现在发现我误解了这个问题。我认为 Keith 的回答会对您有所帮助。

标签: java exception file-io


【解决方案1】:

调用 writeHtmlFile 的代码必须捕获(或重新声明以抛出)IOException。由于调用代码在静态初始化器中,所以一定是前者。

【讨论】:

  • 代码调用writeHtmlFile方法抛出异常导致“非法表达式”错误
  • 确实如此。您不能从静态初始化程序内部抛出(检查的)异常。你必须抓住它。在呼叫周围使用try/catch 块。更好的是,不要让它成为一个静态初始化器,让它成为一个方法,比如main。然后你可以声明它抛出 IOException 并完成它。
猜你喜欢
  • 1970-01-01
  • 2015-07-21
  • 2012-02-20
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-19
相关资源
最近更新 更多