Exception handling in java with examples program
Exception handling in java with eclipse IDE example program and its output
program1
package javaproject1;
public class ExceptionDemo {
public static void main(String[] args) {
String[] fruit_array = {"apple","orange","grapes"};
System.out.println(fruit_array[2]);
System.out.println(fruit_array[3]);
System.out.println(fruit_array[1]);
}
}
program 1 output
Listen to the program 1, line number 9,10,11.
line 9 no error
Line 10 an error occurred
Therefore the rest of the statement is not executed(line 11)
Let's see how the error occurred and how to fix it.
In our program the array length is three.
Array values are arranged starting from zero index.
Let's see how the array values are arranged in this program starting from zero index.
fruit_array[0]-->apple in zeroth position
fruit_array[1]-->orange in first position
fruit_array[2]-->grapes in second position
so fruit_array[3] is out of bound
This will generate an error.
Let's solve this problem with a try catch block.
observe program 2 and its output carefully.
program 2
package javaproject1;
public class ExceptionDemo {
public static void main(String[] args) {
String[] fruit_array = {"apple","orange","grapes"};
try {
System.out.println(fruit_array[2]);
System.out.println(fruit_array[3]);
}
catch(Exception e) {
System.out.println(e);
}
System.out.println(fruit_array[1]);
}
}
short explanation of exception handlng in java
short note in try catch block
Comments
Post a Comment