Java exception handling

How do I use exceptions and exception handling to make my program continue even if an exception occurs while processing certain files in a set of files?

I want my program to work fine for correct files while for those files which cause an exception in program, it should ignore.

Regards,

magggi


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

You have to use the try/catch/finally blocs.

try{  
    //Sensitive code  
} catch(ExceptionType e){  
    //Handle exceptions of type ExceptionType or its subclasses  
} finally {  
    //Code ALWAYS executed  
}
  • try will allow you to execute sensitive code which could throw an exception.
  • catch will handle a particular exception (or any subtype of this exception).
  • finally will help to execute statements even if an exception is thrown and not catched.

In your case

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.
        }
    }
}

Resources :

  • oracle.com - Lesson: Exceptions
  • JLS - exceptions