未报告的异常java.io.FileNotFoundException; 必须被抓住或宣布被抛出

use*_*236 3 java exception try-catch filenotfoundexception

我正在创建一个类 - 只是一个类,没有main(),我收到的错误是"未报告的异常java.io.FileNotFoundException;必须被捕获或声明被抛出"在这一行:

FileOutputStream outStr = new FileOutputStream(FILE, true);   
Run Code Online (Sandbox Code Playgroud)

我不明白; 我输入了一个try {} catch {}块,它仍然报告错误.

此外,它还报告了尝试和两个捕获线的"非法类型开始",它也说';' 预计两条捕获线.

我正在使用NetBean IDE,仅供参考.

感谢您的任何帮助.

这是完整的代码:

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

    }

}
Run Code Online (Sandbox Code Playgroud)

cli*_*unk 9

您需要将文件处理语句放在方法中:

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());
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

43767 次

最近记录:

12 年,6 月 前