You are on page 1of 3

Exception exercise

1. Determine the output of the following code when the input is (a) –1, (b) 0, and (c) 12XY.
This is the same question as Exercise 1, but the code here has the finally clause.

try{
number = Integer.parseInt( JOptionPane.showInputDialog(null,
"input"));

if (number != 0) {
throw new Exception("Not Zero");
}
}
catch (NumberFormatException e) {
System.out.println("Cannot convert to int");
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}finally {
System.out.println("Finally Clause Executed");
}

2.
2. Determine the output of the following code.

import java.util.*;

public class Exception_Example {

public static void main(String a[]){

double[] rainfall = {23.1,98.4,11,101.33} ;


int i,size;

//display rainfall values


for(i=0;i<6;i++){
try{
if(rainfall[i]>100){
throw new Exception("Rainfall value outside range ");
}
System.out.println(rainfall[i]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("You got an error with array index");
System.out.println("the array index that produce error is : "
+ e.getMessage());
break;
}
catch(Exception e){
System.out.println("Error : " + e.getMessage());
System.out.println();
}
finally{
System.out.println("program loops");
}
}//end for loop

}//end main function


}

You might also like