【发布时间】:2018-02-04 15:52:52
【问题描述】:
我正在尝试熟悉 Java 中的文件 I/O。我一开始在编译时遇到了很多错误,例如error: unreported exception IOException; must be caught or declared to be thrown。所以我对代码做了一些修改,最终得到:
public static void main(String[] args){
FileInputStream in = null;
FileOutputStream out = null;
String content = "hello";
byte[] contentBytes = content.getBytes();
try{
out = new FileOutputStream("output.txt");
out.write(contentBytes);
}catch(IOException e){
}catch(FileNotFoundException e){
}
finally{
if (out != null)
out.close();
}
}
不过,我得到了这个错误:
FileIO.java:16: error: exception FileNotFoundException has already been caught
}catch(FileNotFoundException e){
^
FileIO.java:21: error: unreported exception IOException; must be caught or declared to be thrown
out.close();
^
2 errors
- 我在哪里“已经抓住”
FileNotFoundException? - 由于第二个错误,是否需要在
finally子句中再添加一个try和catch语句来捕获IOException?这看起来很混乱而且过于复杂。我做错了什么吗?为什么 java 不让我做我想做的事而不强迫我捕获异常?
编辑:
如果我这样做:
public static void main(String[] args){
FileOutputStream out = null;
String content = "hello";
byte[] contentBytes = content.getBytes();
try{
out = new FileOutputStream("output.txt");
out.write(contentBytes);
}catch(FileNotFoundException e){
}catch(IOException e){
}
finally{
if (out != null)
out.close();
}
}
我明白了:
FileIO.java:20: error: unreported exception IOException; must be caught or declared to be thrown
out.close();
^
1 error
【问题讨论】:
-
您的其他问题可能在这里得到解答:Java catching exceptions and subclases。虽然我建议坚持每个帖子一个问题,以便为每个问题获得更好的答案,并使帖子对其他人更有用。
-
@Ravi 该帖子目前提出了两个不同的问题 - 可能需要对问题主体进行相当重要的编辑(作者)以证明仅关注其中一个的标题(尽管答案会使这样的编辑有问题)。
-
@Dukeling 你是在建议我回滚吗?
-
@Ravi 差不多,如果你愿意的话。虽然我不太介意,因为我认为这个问题应该被关闭,因为它过于宽泛或重复。
-
@Dukeling 我回滚到旧更改。我想使标题更有意义,以便人们可以轻松搜索。但是,我同意你的观点。 :-)
标签: java