如何处理“异常;必须被捕获或宣布被抛出”?

时间:2015-12-30 05:42:53

标签: java overwrite

我正在尝试编写一个覆盖我正在处理的文件的测试文件,这样我就可以将它用于更复杂的程序。我一直收到与创建新PrintWriter相关的错误消息。

这是错误消息:

  

未报告的异常java.io.FileNotFoundException;必须被抓住或   宣布被抛出       PrintWriter printWriter = new PrintWriter(file);

这是我的代码:

import java.io.PrintWriter;
import java.io.File;


public class rewriting_test_file { 

    public static void main(String[] args) {

        File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
        file.getParentFile().mkdirs();
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close ();      
    }
}

2 个答案:

答案 0 :(得分:1)

如错误所示,您需要抛出异常或在try / catch块中捕获它。看一下Exception handling教程

public static void main(String[] args) throws IOException
    {

    File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
    file.getParentFile().mkdirs();
    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close ();      
        }
    }

public static void main(String[] args) 
    {
     PrintWriter printWriter = null;
   try{
      File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
      file.getParentFile().mkdirs();
      printWriter = new PrintWriter(file);
      printWriter.println ("hello");

        }
       catch(IOException e){
          e.printStackTrace();
       }
       finally{
           if(printWriter!=null)
             printWriter.close ();   //always close the resources in finally block
       }
      }
    }

答案 1 :(得分:0)

错误消息说明了一切。

如果您提供的文件不存在,则创建PrintWriter 可能会抛出FileNotFoundException

您必须将其包装在try/catch块中:

try{
    PrintWriter pw = new PrintWriter(file);
    //do more stuff
}catch(FileNotFoundException e){
    System.out.println("File doesn't exist. Here's the stack trace:");
    e.printStackTrace();
}

或者,声明您的方法抛出异常:

public static void main(String[] args) throws IOException { //...