Cha*_*ixy 6 java eclipse compiler-errors unhandled-exception
是否有可能让Eclipse忽略错误"未处理的异常类型"?
在我的具体情况下,原因是我已经检查过该文件是否存在.因此,我认为没有理由加入try catch语句.
file = new File(filePath);
if(file.exists()) {
FileInputStream fileStream = openFileInput(filePath);
if (fileStream != null) {
Run Code Online (Sandbox Code Playgroud)
或者我错过了什么?
是否有可能让Eclipse忽略错误"Unhandled exception type FileNotFoundException".
不会.这将是无效的Java,Eclipse不允许您更改语言规则.(你有时可以尝试运行不能编译的代码,但它不会做你想要的.你会发现UnresolvedCompilationError当执行到达无效代码时会抛出它.)
另请注意,仅仅因为调用时文件存在file.exists()并不意味着当您尝试稍后打开它时它仍然存在.它可能在此期间被删除.
您可以做的是编写自己的方法来打开文件,如果文件不存在则抛出未经检查的异常(因为您对它有信心):
public static FileInputStream openUnchecked(File file) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
// Just wrap the exception in an unchecked one.
throw new RuntimeException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,"unchecked"在这里并不意味着"没有检查" - 它只是意味着抛出的唯一异常将是未经检查的异常.如果你找到一个更有用的不同名称,那就去吧:)