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

如何在Java中捕获异常后继续执行程序,java,exception,exception-handling,error-handling,terminate,Java,Exception,Exception Handling,Error Handling,Terminate,我的程序在一些文件夹中循环,并将文件夹中的文件复制到具有新名称的新文件中。一些文件将被复制,而另一些文件将出现Java异常,表示访问被拒绝。当这种情况发生时,程序终止。我希望它跳过,而不是复制那个文件,然后继续。这里是复制函数 private static void copyFile(File source, File dest) throws IOException { FileChannel inputChannel = null; FileChannel o

我的程序在一些文件夹中循环,并将文件夹中的文件复制到具有新名称的新文件中。一些文件将被复制,而另一些文件将出现Java异常,表示访问被拒绝。当这种情况发生时,程序终止。我希望它跳过,而不是复制那个文件,然后继续。这里是复制函数

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();
    }
}
任何帮助都会很好。谢谢

变化

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

并从
copyFile(文件源,文件目的)
方法中删除
抛出IOException

现在你的方法是这样的

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

}

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

如下所示(还包括Prabhakaran关于空检查值的建议):


只需在调用您的
copyFile
方法的程序中捕获异常,然后继续。我删除copyFile方法中的catch块的原因是它允许通常使用copyFile方法(在异常期间可能希望停止处理的时间和希望忽略异常的时间)

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

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