error: unreported exception FileNotFoundException; must be caught or declared to be thrown

后端 未结 4 1758
再見小時候
再見小時候 2020-12-06 11:12

I\'m trying to create a simple program that will output a string to a text file. Using code I found here, I have put together the following code:

import jav         


        
4条回答
  •  庸人自扰
    2020-12-06 11:22

    You are not telling the compiler that there is a chance to throw a FileNotFoundException a FileNotFoundException will be thrown if the file does not exist.

    try this

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File ("file.txt");
        file.getParentFile().mkdirs();
        try
        {
            PrintWriter printWriter = new PrintWriter(file);
            printWriter.println ("hello");
            printWriter.close();       
        }
        catch (FileNotFoundException ex)  
        {
            // insert code to run when exception occurs
        }
    }
    

提交回复
热议问题