Tuesday, January 25, 2011

Handling exceptions.

In java we use try catch to handle exception. In try we write the code which we think can/might cause the exception and in catch we write the solution to fix if the exception occurs.


class TryCatchTest{

public static void main(String[] args){

try{

double value = Double.parseDouble(args[0]);

double result = Math.sqrt(value);

System.out.printf("Square-root of %f is %f%n",

value, result);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("USAGE: java TryCatchTest number");

}catch(Exception e){

System.out.printf("ERROR: %s!%n", e);

}

System.out.println("Done!");

}

}

To compile:

javac TryCatchTest.java

To run:

java TryCatchTest

No comments: