Magggi
Magggi

Reputation: 1155

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

Upvotes: 7

Views: 12856

Answers (8)

Raiyan Shahid
Raiyan Shahid

Reputation: 49

Exception in java are runtime error which can be handled by the program, the process is called as exception handling. Parent class of exception is Throwable. Exception : Exception are those runtime error which can be handled by program.

Error : Those runtime error which can’nt handled by the program.

Tools used to handle Exception:

Try Catch Finally Throw Throws

more

Upvotes: 0

Jayswal Mihir
Jayswal Mihir

Reputation: 1

public class Main
{
    public static void main(String args[])
    {
        int a=10;
        try
        {
            System.out.println(a/0); //Here it is not possible in maths so it goes to catch block 
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception");
        }
    }
}

output:Arithmetic Exception

Upvotes: 0

Vamshi Rakela
Vamshi Rakela

Reputation: 43

FileSystemException may be the specific exception you are looking for.

Although, a better idea for beginners is to catch an exception and print it using

System.out.println(e);

where e is the caught exception.

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

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

Upvotes: 17

Colin Hebert
Colin Hebert

Reputation: 93157

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 :

Upvotes: 11

bragboy
bragboy

Reputation: 35542

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
}

Upvotes: 0

JonWillis
JonWillis

Reputation: 3147

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.

Upvotes: 2

nkr1pt
nkr1pt

Reputation: 4666

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
}

Upvotes: 0

Related Questions