Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 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 Answer

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());
        } 
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...