/*
* If you compile this code, it would compile
* successfully however when you will run it, it would
* throw ArrayIndexOutOfBoundsException. That clearly shows that
* unchecked exceptions are not checked at compile-time,
* they are being checked at runtime.
*/
public class UnCheckedExceptionDemo1
{
public static void main(String[] args)
{
int intArray[] = { 1, 2, 3 };
/*
* intArray has only 3 elements but I'm trying to
* display the value of 6th element. It should throw
* ArrayIndexOutOfBoundsException
*/
System.out.println(intArray[5]);
System.out.println("Normal flow...");
}
}
Output Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at UnCheckedExceptionDemo1.main(UnCheckedExceptionDemo1.java:20)
UnCheckedExceptionDemo2.java import java.util.Scanner;
public class UnCheckedExceptionDemo2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the index: ");
int index = scanner.nextInt();
scanner.close();
try
{
int intArray[] =
{ 155, 345, 999 };
System.out.println(intArray[index]);
}
catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException)
{
System.out.println("Enter the index value less "
+ "than or equal to 2,\nbecause "
+ "size of the array is 3");
}
System.out.println("Normal flow...");
}
}