Exception handling and Recursion.


An exception  in Java is an event that occurs during the execution of a program that DISRUPTS the normal flow of instructions. But in real practice exceptions are abused to manage business logic. In java all exceptions are dervied from Throwable class, which defines many methods. To handle exception java has try and catch blocks.


Following program illustrates exception handling using try and catch block.  Command line arguments are scanned for two numbers and converted in to double values. If the arguments are not passed try block throws an exception. If the exception is caught exception block calls getNumber function. getNumber function also checks for exception repeatedly. Here we used the recursion mechanism to ask for number repeatedly.  Visit nearest  MICE  center to know more about java and other  computer courses offered.


package ravi;

import java.lang.*;
import java.io.*;

public class AddNumber {

public static void main(String args[]) {
double no1, no2, result;
result = no1 = no2 = 0.0;
try {
no1 = Double.parseDouble(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
no1 = getNumber("Number 1:");
} catch (NumberFormatException e1) {
no1 = getNumber("Number 1:");
} catch (Exception e2) {
no1 = getNumber("Number 1:");
}
try {
no2 = Double.parseDouble(args[1]);
} catch (Exception  e) {
no2 = getNumber("Number 2:");
}

result = no1 + no2;

System.out.println("Sum :" + result);

}

public static double getNumber(String msg) {
double rv = 0.0;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print(msg);
try {
rv = Double.parseDouble(bf.readLine());
} catch (IOException e1) {
System.out.println(e1.getMessage());
System.exit(0);
} catch(NumberFormatException e2) {
System.out.println("Please enter proper number!");
rv = getNumber(msg);
}
return rv;
}

}

Comments