Tuesday, May 8, 2007

Exception Example


try
{

This is where your logic goes like Opening a file
reading a file closing a file,etc

}
catch(FileNotFoundException ff)
{

This gets executed when the expected file is not found

}
catch(IOException ie)
{

This gets executed when the read or write operation failed

}
finally
{

This always executes when the try block exits.The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.

}



So far we have seen scenarios where it's appropriate for code to catch exceptions
that can occur within it.In some cases, however, it's better to let a method further
up the call stack handle the exception.In this case, it's better to not catch the
exception and to allow a method further up the call stack to handle it.

This can be done by modifying the method to specify the exceptions it can throw ,
instead of catching them.

For example


public void methodName() throws IOException{}


Java provides numerous classes of exception.All the exception classes are descendant
of Throwable class.

User can create his own exception class by extending the Throwable class. Java
doesnot provide any interfaces for creating exception classes.

No comments: