为什么我的catch块不工作?
我试图测试出throws FileNotFoundException
。起初,我将我的exec.txt
放在我的项目文件夹中,以测试我的"testing"
字符串&当我运行我的程序时它工作正常。为什么我的catch块不工作?
但现在,我从我的文件夹中删除我的exec.txt
文件,看看是否catch()
部分在main
方法将工作,但事实并非如此。 catch()
部分的File not found
部分不会出现在控制台中。
import java.io.*;
public class Crashable {
public static void openFile(String f) throws FileNotFoundException {
PrintWriter f1 = new PrintWriter(f);
f1.write("testing");
f1.close();
}
public static void main(String[] args) {
String f = "exec.txt";
try {
openFile(f);
} catch(FileNotFoundException e) {
System.out.println("File not found");
}
}
}
如文档中说,当一个文件无法访问或创建的FileNotFoundException
将被抛出。
发生其他一些错误给定的字符串不表示现有的可写常规文件,并且该名称的新常规文件不能被创建,或FileNotFoundException异常 - 如果如果在打开或创建文件
在你的情况下,它可以创建一个新文件,所以不会抛出异常。
你可以得到它试图在不存在的目录创建文件扔execption:
String f = "zzz/exec.txt"
你永远不抛出异常的openFile
方法。从Java docs,
公众的PrintWriter(File file)在 抛出FileNotFoundException异常
创建一个新的PrintWriter,没有自动行刷新的指定文件。此便利构造函数创建必需的 中间OutputStreamWriter,它将使用 这个Java虚拟机实例的默认字符集对字符进行编码。
参数: file - 要用作此作者目标的文件。如果文件存在,则它将被截断为零大小;否则,将会创建一个新的 文件。输出将被写入文件并且被缓冲,并且是 。
因此,如果文件不存在,您将创建一个新文件。所以基本上,一切正常,因为虽然文件不存在,但当您创建PrintWriter
对象时,它会创建一个新文件,但不会引发错误。
PrintWriter f1 = new PrintWriter(f); f1.write("testing"); f1.close();
相反试试这个:
您正在使用这段代码,每次实际创建一个新的文件
public static void openFile(String f) throws FileNotFoundException {
File file = new File(f);
if(!file.exists())
{
throw new FileNotFoundException();
}
else
{
//do Something with the file
}}
希望它可以帮助..
重新阅读PrintWriter构造函数的文档:“如果文件存在,则它将被截断为零大小;否则,将创建一个新文件。”只有在无法创建文件时才抛出异常。 – yshavit