我可以设置Eclipse忽略“未处理的异常类型” [英] Can I set Eclipse to ignore "Unhandled exception type"

查看:268
本文介绍了我可以设置Eclipse忽略“未处理的异常类型”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能让Eclipse忽略错误未处理的异常类型?



在我的具体情况下,原因是我已经检查了文件存在。因此,我看不到放在try catch语句中的原因。

  file = new File(filePath); 
if(file.exists()){
FileInputStream fileStream = openFileInput(filePath);
if(fileStream!= null){

>

解决方案


有可能让Eclipse忽略错误未处理的异常类型FileNotFoundException。


否。这将是无效的Java,并且Eclipse不允许您更改语言的规则。 (你有时可以尝试运行不编译的代码,但是它不会做你想要的,你会发现执行到无效的时候会抛出 UnresolvedCompilationError 代码。)



还要注意,只是因为当您调用 file.exists()时文件存在意味着在您稍后尝试打开它时仍然存在。

你可以自己写一个方法来打开一个文件,并抛出一个未检查的异常if该文件不存在(因为你确信它是):

  public static FileInputStream openUnchecked {
try {
return new FileInputStream(file);
} catch(FileNotFoundException e){
//只需将异常包含在未选中的异常中。
throw new RuntimeException(e);
}
}

请注意,未选中没有检查 - 它只是意味着抛出的唯一异常将是未检查的异常。如果你发现一个不同的名称更有用,然后去:)


Is it possible to get Eclipse to ignore the error "Unhandled exception type"?

In my specific case, the reason being that I have already checked if the file exists. Thus I see no reason to put in a try catch statement.

file = new File(filePath);
if(file.exists()) {         
    FileInputStream fileStream = openFileInput(filePath);           
    if (fileStream != null) {

Or am I missing something?

解决方案

Is it possible to get Eclipse to ignore the error "Unhandled exception type FileNotFoundException".

No. That would be invalid Java, and Eclipse doesn't let you change the rules of the language. (You can sometimes try to run code which doesn't compile, but it's not going to do what you want. You'll find that UnresolvedCompilationError is thrown when execution reaches the invalid code.)

Also note that just because the file existed when you called file.exists() doesn't mean that it still exists when you try to open it a tiny bit later. It could have been deleted in the meantime.

What you could do is write your own method to open a file and throw an unchecked exception if the file doesn't exist (because you're so confident that it does):

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);
    }
}

Note that "unchecked" here doesn't mean "there's no checking" - it just means that the only exceptions thrown will be unchecked exceptions. If you'd find a different name more useful, then go for it :)

这篇关于我可以设置Eclipse忽略“未处理的异常类型”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆