Credits

Saturday, January 8, 2011

Exception Handling using Try - Catch Blocks

 Exceptions or errors are normally interchanged but exceptions may be attributed to compilation errors and logic bugs. But, normally, if there are wrong user inputs (e.g. letters instead of numbers), exception handling can be used to let the system run without glitches.

The try and catch blocks can be used to respond to exceptions. However, syntax errors and logic errors should be properly addressed.

The  program below  checks whether the divisor is zero or not otherwise an exception is caught.

[+/-] show/hide


/* program for try and catch */
import java.lang.*;
import java.io.*;
public class TryDemo2{
public static void main ( String args[]) throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));

System.out.println("Input a numerator:");
String numerator=stdin.readLine();
int num1=Integer.parseInt(numerator);
System.out.println("Input a divisor:");
String divisor=stdin.readLine();
try{

int num2=Integer.parseInt(divisor);
System.out.println("The quotient of "+numerator+" and "+divisor+" is "+num1/num2);
}
catch (ArithmeticException ex){
System.out.println("Wrong data! "+ex);//to display the error msg

System.out.println("Division by zero! ");
}
System.out.println("Goodbye!");
}

}

AddThis