tags:

views:

161

answers:

5

Hi all,

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

+8  A: 

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 :

Colin Hebert
I am aware of that.Problem: 1.My application processes multiple files. 2.Any of the files can fail while processing.(exception) 3.But now my application exits wen any 1 file fails. 4.I want my application ot continue executing other files.So how should i structure my exception handling?
You should put all your exception handling in your loop.
Colin Hebert
A: 

just catch the excpetion it may throw and do nothing with it; eat it as people say :) But at least log it!

Very concise example:

try {
   your code...
} catch (Exception e) {
   log here
}
nkr1pt
+1  A: 

Hi Magggi.

I guess your new to programming as execeptions are a fairly fundermental concept, as problems can happen out of your control and you need to deal with it.

The basic premise is a try catch block.

try
{
    //Your code here that causes problems
}
catch(exception ex)
{
    //Your code to handle the exception
}

You 'try' your code, and if an exception is raised, you 'catch' it. And do what you need. There is also an addition to the catch block in that you can add finally{} below it. Basically even if no exception is raised the finally code is still run. You may wonder the point in this, but its often used with streams/file handling etc to close the stream.

Read more on java exceptions here in tutorials written by Sun (now Oracle)- http://download.oracle.com/javase/tutorial/essential/exceptions/

try
{
    //Your code here that causes problems
}
catch(exception ex)
{
    //Your code to handle the exception
}
finally
{
    //Always do this, i.e. try to read a file, catch any errors, always close the file
}

The question you may ask is how do you catch different exceptions, i.e. is it a null reference, is it divide by zero, is it no file found or file not writeable etc. For this you write several different catch blocks under the try, basically one catch for each type of exception, the use of "exception" is basically a catch all statement, and like in stack of if statements if an "exception" is the first catch block it will catch everything, so if you have several catch blocks ensure exception is the last one.

Again, this is a useful but large topic so you need to read up about it.

Since you are doing multiple files, you need to basically do a loop and within the loop is contained the try/catch block.

so even if one file fails, you catch it, but carry on running, the code will then loop around onto the next file unhindered.

JonWillis
+10  A: 
for(File f : files){
   try {
       process(f); // may throw various exceptions
   } catch (Exception e) {
       logger.info("Could not process file "+f.getName()+
                   " because of exception: "+e.toString());
   }
}
Michael Borgwardt
+1 for the meaningful log message (including the file name). Most code I see has just `logger.info(e.getMessage())`.
Thilo
It may be better style to not catch the general Exception type but rather specific exception types (IOException,...).
boutta
Although in practice, if you are opening a connection to the file, you will want to add a finally block in which to close the connection as per Colins answer.
Joel
Is there a reason for not logging the stacktrace ? I find the exception message is often not enough to understand a problem and reproduce it.
Thierry
@Thierry: Stack traces are useful for solving bugs in the code; It sounded to me like the question was more about things like FileNotFoundException where the stack trace is not useful.
Michael Borgwardt
You are correct.But with this logic the program would exit after logging the measage. * But what if there are some more files remaining? * I want to process the remaining files even after the exception..
@magggi: Um, no. The catch block handles the exception and the loop continues as if nothing had happened.
Michael Borgwardt
U were correct..thanks a lot..
A: 

Typically, I would have done this.

ArrayList<Entry> allEntries = getAllEntries();

for(Entry eachEntry:allEntries){
  try{
    //do all your processing for eachEntry
  } catch(Exception e{
     ignoredEntries.add(eachEntry);
     //if concerned, you can store even the specific problem.
  } finally{
     //In case of resource release
  }
}

if(ignoredEntries.size() > 0){
  //Handle this scenario, may be display the error to the user
}
Bragboy