如何在Java中捕获异常后继续执行程序

时间:2013-12-02 00:51:05

标签: java exception exception-handling error-handling terminate

我的程序循环浏览一些文件夹,并将文件夹中的文件复制到一个新名称的新文件中。某些文件将被复制,其他文件将获得Java Exception,表示拒绝访问。当发生这种情况时,程序终止。我希望它跳过而不是复制该文件并继续前进。这是复制功能。

private static void copyFile(File source, File dest)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } catch (Exception e){

    }


        finally{
    inputChannel.close();
    outputChannel.close();
    }
}

任何帮助都会很棒。谢谢!

3 个答案:

答案 0 :(得分:2)

只需将调用程序中的异常捕获到copyFile方法并继续。我在copyFile方法中删除catch块的原因是它允许一般使用copyFile方法(在异常期间可能希望停止处理的次数以及想要忽略异常的时间)。

...
for (File source : sources) {
   try {
      copyFile(source, dest);
   }
   catch (Exception ignore) {
      // ignore exception and continue
   }
   // do your other stuff here
}

private static void copyFile(File source, File dest)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } 
    finally{
       if (inputChannel != null) inputChannel.close();
       if (outputChannel != null) outputChannel.close();
    }
}

答案 1 :(得分:0)

变化

finally{
       inputChannel.close();
       outputChannel.close();
}

finally{
   try {
         if(inputChannel!=null)
            inputChannel.close();
         if(outputChannel!=null)   
            outputChannel.close();         
    } catch (Exception e){

    }
}

并从throws IOException方法

中删除copyFile(File source, File dest)

现在你的方法看起来像这样

private static void copyFile(File source, File dest){

}

答案 2 :(得分:0)

catch块中,您可以使用continue语句“跳过”当前正在处理的文件。

如下所示(也包含Prabhakaran建议的空检查值):

private static void copyFile(File source, File dest)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } catch (Exception e) {
        // You should be logging any exception here. Empty blocks == bad practice.
        continue;
    } finally {
        if(inputChannel != null {
            inputChannel.close();
        }
        if(outputChannel != null {
            outputChannel.close();
        }
    }
}