[英]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: 我正在创建一个类 - 只是一个类,没有main(),我收到错误的“未报告的异常java.io.FileNotFoundException;必须被捕获或声明被抛出”在这一行:
FileOutputStream outStr = new FileOutputStream(FILE, true);
I don't understand; 我不明白; I put in a try{} catch{} block and it's still reporting the error. 我输入了一个try {} catch {}块,它仍然报告错误。
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. 我正在使用NetBean IDE,仅供参考。
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());
}
}
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());
}
}
}
All functional code needs to go into methods - I don't see a method in your code - that's the illegal start of type problem. 所有功能代码都需要进入方法 - 我没有在你的代码中看到一个方法 - 这是类型问题的非法开始。 The other compile errors should become clearer once you get the basics down. 一旦你掌握了基础知识,其他编译错误就会变得更加清晰。
public class Foo {
public void doSomething() {
//code here
}
}
将此代码移动到某个方法或至少移动到静态初始化程序块。
import java.io.*;
import java.util.*;
public class SortNames {
private String[] strings = new String[10];
private int counter;
public SortNames() {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = null;
File f = null;
try{
f = new File("names.txt");
scan = new Scanner(f);
while(scan.hasNext()) names.add(scan.next());
}
finally{scan.close();}
Collections.sort(names);
for(String s:names) System.out.println(s);
}
}
Sorry if this isn't helpful to you, but I was able to solve this exact issue by adding " throws FileNotFoundException " to my method call that contained the FileWriter. 很抱歉,如果这对您没有帮助,但我能够通过在包含FileWriter的方法调用中添加“throws FileNotFoundException”来解决这个问题。 I know this may not be helpful since you aren't using methods, but then again, maybe it is. 我知道这可能没有用,因为你没有使用方法,但话说回来,也许是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.