Program :To demonstrate exception handling.
Program
package exam; import java.io.*; public class MyArrExce { public static void main(String args[]) { int n=0,i,j,t; int a[]=new int[5]; DataInputStream in= new DataInputStream(System.in); try { System.out.println("Enter the no: of elements : "); n=Integer.parseInt(in.readLine()); System.out.println("Enter the elements of array : "); for(i=0;i<n;i++) a[i]=Integer.parseInt(in.readLine()); for(i=0;i<n;++i) for(j=i+1;j<n;j++) if(a[i]<a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } System.out.println("The sorted array is : "); for(i=0;i<n;i++) System.out.println(a[i]+" "); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error : Array index out of bounds."); System.exit(0); } catch(Exception e) { System.out.println("Error : "+ e ); System.exit(0); } } } |
Output
Enter the no: of elements :
5
Enter the elements of array :
23
6
36
99
10
The sorted array is :
99
36
23
10
6
Enter the no: of elements :
6
Enter the elements of array :
23
6
36
99
10
29
Error : Array index out of bounds.
Leave a Reply