Credits

Wednesday, January 6, 2010

Exception Handling of Java

Exceptions or abnormal disruptions or errors may occur in any program. But a well written and well thought program may reduce the occurrence of any error or at least handle gracefully these errors.


In Java, exceptions can be handled as if the errors did not occur at all. These are in the forms of user or inherent exception methods.


Typical exception can be invalid input, math errors, array out of size and many others. An exception can be thrown try the use of these keywords: try, catch, finally, throws, and throw.


For a program not to be interrupted  during execution because of wrong input format, a sample try and catch block like below can be given.



[+/-] show/hide



/* program for try and catch */
import java.lang.*;
import java.io.*;
public class TryDemo1{
public static void main ( String args[]) throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));
String inData;
System.out.println("Input an integer:");
inData=stdin.readLine();
try{
int num=Integer.parseInt(inData);
System.out.println("The square of "+num+" is "+num*num);
}
catch (NumberFormatException ex){
System.out.println("Wrong data! See error cause: "+ex);//to display the error msg

}
System.out.println("Goodbye!");
}

}

AddThis