我可以避免Java中的catch块吗?

时间:2012-12-14 16:05:55

标签: java exception try-catch

在方法中,我使用扫描仪读取文件内的文本。这个文件并不总是存在,如果不存在,我只想做什么(即没有扫描)。 当然我可以使用这样的try / catch:

String data = null;
try
{
    Scanner scan = new Scanner(new File(folder + "file.txt"));
    data=scan.nextLine();
    scan.close();
}
catch (FileNotFoundException ex)
{
}

我的问题是如何避免try / catch?因为我不喜欢局部变量未使用。我想的是:

String data = null;
File file_txt = new File(folder + "file.txt");
if (file_txt.exists())
{
    Scanner scan = new Scanner(file_txt);
    data=scan.nextLine();
    scan.close();
}

但当然有了这个我在Netbeans中出错了,我无法构建我的项目......

3 个答案:

答案 0 :(得分:5)

,已检查异常。必须使用try阻止和/或catch阻止finally。有两种处理已检查异常的方法。

方法1:使用try/catch/finally

包装您的代码

选项1

try{
    Scanner scan = new Scanner(new File(folder + "file.txt"));
    data=scan.nextLine();
    scan.close();

}
catch (FileNotFoundException ex)
{
   System.out.println("Caught " + ex);
}

选项2

try{
    Scanner scan = new Scanner(new File(folder + "file.txt"));
    data=scan.nextLine();
    scan.close();

}
finally
{ 
      System.out.println("Finally ");
}

选项3

    try{ 
     Scanner scan = new Scanner(new File(folder + "file.txt"));
     data=scan.nextLine();
     scan.close();
     }catch(FileNotFoundException ex){
          System.out.println("Caught " + ex );
     }finally{
          System.out.println("Finally ");
     }  

方法2:使用throw抛出异常,并使用throws子句列出所有异常。

    class ThrowsDemo {

    static void throwOne() throws IllegalAccessException {
        System.out.println("Inside throwOne.");
        throw new IllegalAccessException("demo");
    }

    public static void main(String args[]) {
        try {
            throwOne();
        } catch (IllegalAccessException e) {
            System.out.println("Caught " + e);
        }
    }
    }

注意: Checked Exception意味着编译器会强制您编写一些内容来处理此错误/异常。因此,除了上述方法之外,AFAIK除了检查异常处理之外没有任何替代方法。

答案 1 :(得分:2)

FileNotFoundException被检查异常,由于catch or specify behavior,您需要在方法声明的throws子句中捕获(或)指定它。

答案 2 :(得分:1)

怎么样

   catch (FileNotFoundException ex)
   {
       // create a log entry about ex
   }
相关问题