Credits

Thursday, July 29, 2010

Catch Errors through Exceptions

 Exceptions in Java can come in 3 forms: errors, runtime exceptions and logical exceptions. Errors and logical exceptions should be corrected as these affect the program's reliability and accuracy. However, runtime exceptions like division by zero, wrong input format, array access out of size, and etc. However, Java can handle these exception through try -- catch blocks.


Typically, NumberFormatException is encountered when a non-numeric input is encoded for a number input. This shall cause a program disruption that shows up the stack trace or the causes of disruption and from what method among other information.


The sample program below shows the use of exception.

[+/-] 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 myInput;
System.out.println("Input an integer:");
myInput=stdin.readLine();
try{
int num=Integer.parseInt(myInput);
System.out.println("The square of "+num+" is "+num*num);
}
catch (NumberFormatException ex){
System.out.println("You have encoded a wrong input");
}
System.out.println("Goodbye!");
}

}

AddThis