【发布时间】:2014-04-19 15:06:44
【问题描述】:
我有以下代码需要捕获AccessDeniedException 异常
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
class MyFileClass {
public void write()
throws IOException
{
PrintWriter out = new PrintWriter("sample.txt");
out.printf("%8.2f\n", 3.4);
out.close();
}
}
public class MyClass {
public static void main(String[] args)
throws Exception
{
try {
MyFileClass mf = new MyFileClass();
mf.write();
} catch (AccessDeniedException e) {
print("Access denided");
}
catch (FileNotFoundException e) {
print("File not found");
}
}
}
如果 sample.txt 是只读的,我会得到“file not found”而不是“Access Denied”的输出。我想了解这是什么原因?另外,上述捕获AccessDeniedException的结构是否正确?
【问题讨论】:
-
不打印,使用e.printStackTrace()在控制台获取详细的错误信息
-
打印完整的异常堆栈跟踪并粘贴
-
当文件没有设置为只读时,程序能找到文件吗?
标签: java file exception exception-handling