Credits

Thursday, July 29, 2010

Another illustration of exception handling is the use of exception type, ArithmeticException which is normally used for division by zero among other arithmetic operations.

See the program below for this example.

[+/-] 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("Division by zero! ");
}

}

}

AddThis