Java异常处理

Mag*_*ggi 5 java exception

即使在处理一组文件中的某些文件时发生异常,如何使用异常和异常处理来使我的程序继续?

我希望我的程序能够正常处理正确的文件,而对于那些导致程序异常的文件,它应该忽略.

问候,

magggi

Mic*_*rdt 15

for(File f : files){
   try {
       process(f); // may throw various exceptions
   } catch (Exception e) {
       logger.error(e.getMessage(), e);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然在实践中,如果要打开与文件的连接,您将需要添加一个finally块,根据Colins的答案关闭连接. (2认同)

Col*_*ert 11

你必须使用try/catch/finally集团.

try{  
    //Sensitive code  
} catch(ExceptionType e){  
    //Handle exceptions of type ExceptionType or its subclasses  
} finally {  
    //Code ALWAYS executed  
}
Run Code Online (Sandbox Code Playgroud)
  • try 将允许您执行可能引发异常的敏感代码.
  • catch 将处理特定异常(或此异常的任何子类型).
  • finally 即使抛出异常而没有捕获异常,也会帮助执行语句.

在你的情况下

for(File f : getFiles()){
    //You might want to open a file and read it
    InputStream fis;
    //You might want to write into a file
    OutputStream fos;
    try{
        handleFile(f);
        fis = new FileInputStream(f);
        fos = new FileOutputStream(f);
    } catch(IOException e){
        //Handle exceptions due to bad IO
    } finally {
        //In fact you should do a try/catch for each close operation.
        //It was just too verbose to be put here.
        try{
            //If you handle streams, don't forget to close them.
            fis.close();
            fos.close();
        }catch(IOException e){
            //Handle the fact that close didn't work well.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

资源:

  • 您应该将所有异常处理放在循环中. (2认同)