Exceptions:

When a error is encountered during the run time of program,it simply terminates without giving any control to the program developer.Instead of simply terminating the program we can provide control to the developer on that error situation.

Exception Handling is usually a Error Trapping Technique provided by java to help the program developers. Exception Handling in java is similar to the one in c++ or Delphi.

Exception Handling is found to be more useful in dealing with errors like

1.User Input errors - Errors associated with the user given input.

2.Device Limitations - Due to temporary unavailability of resources like web pages or printers.

3.Physical Limitations - Unavailability of memory which may be already filled up.

Exception Handling is carried out by using three important key elements in the java programming language.They are

try

throw

catch

try:

The part of code which is anticipated to produce an error is placed in the try block.If an error is encountered the control of the program jumps to the corresponding catch block.

public class example

{

String filename="c:/file.txt";

try

{

InputStream in = new FileInputStream(filename);

int b;

while ((b = in.read()) != -1)

{

System.out.print(in.read());

}

in.close();

}

catch (IOException exception)

{

exception.printStackTrace();

}

}

In the above code,when trying to read the input file "c:/file" it may not be available or it may be in accessible.In this situation the console will throw an error which is catched in the corresponding catch block and the stacktrace elements are printed to display the cause of the error.

throw:

This keyword can be used to throw an exception explicitly.This statement can be placed only in the try block.When the throw statement is encountered during run time then the control jumps to the catch block.

public class example

{

String filename="c:/file.txt";

try

{

if(filename==null)

{

throw new NullPointerException();

}

InputStream in = new FileInputStream(filename);

int b;

while ((b = in.read()) != -1)

{

System.out.print(in.read());

}

in.close();

}

catch(NullPointerException e)

{

e.printStackTrace();

}

catch (IOException exception)

{

exception.printStackTrace();

}

}

catch:

The main purpose of the catch block is to handle those exceptions that corresponds to this block.

This block usually contains the code to resolve those exceptions or it may contain the code to display the cause of the error.It can also be implemented to perform specific actions other than resolving the exceptions.