Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

I am creating a class -- just a class, no main() and I am receiving the error of "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" at this line:

FileOutputStream outStr = new FileOutputStream(FILE, true);   

I don't understand; I put in a try{} catch{} block and it's still reporting the error.

Additionally, it's also reporting an "illegal start of type" for the try and both catch lines, and it's also saying that ';' is expected for both catch lines.

I'm using the NetBean IDE, FYI.

Thank you for any help.

Here is the full code:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileNotFoundException;


public class UseLoggingOutputStream 
{

    String FILE = "c:\system.txt";

    try
    {

        FileOutputStream outStr = new FileOutputStream(FILE, true);

    }

    catch(FileNotFoundException fnfe)
    {

        System.out.println(fnfe.getMessage());

    }

    catch(IOException ioe)
    {

        System.out.println(ioe.getMessage());

    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to put the file processing statements inside a method:

import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class UseLoggingOutputStream {
    public void myMethod() {
        String file = "c:\system.txt";
        try {
            FileOutputStream outStr = new FileOutputStream(file, true);
        } catch(FileNotFoundException fnfe) { 
            System.out.println(fnfe.getMessage());
        } 
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...