Credits

Saturday, January 8, 2011

Java's Multiple Catch Blocks

 Different exceptions can be caught using several catch blocks. However, make sure that you let the specific exception be handled first before allowing the general Exception to catch any other exception.

The program below catch Arithmetic (e.g. negative numbers for dimensions) and Number Format (e.g. string input instead of numbers) exceptions.
[+/-] show/hide

/* program for try and catch */

import java.io.*;
public class TryDemo3{
public static void main ( String args[]) throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));

try{

System.out.println("Input a length for the rectangle:");
int length=Integer.parseInt(stdin.readLine());
System.out.println("Input a width for the rectangle:");
int width=Integer.parseInt(stdin.readLine());
System.out.println("The area of rectangle:"+length*width);

}
catch (ArithmeticException ioe){
System.out.println("Math Error: "+ioe);
System.exit(0);
}
catch (NumberFormatException ne){
System.out.println(ne+" , not a valid input.");
System.exit(0);
}

}

}

AddThis