0

Yea this is a basic Try and Catch error. I am deeepply sorry if this is just a simple question and im wasting your time, but why does it give me the error for IO Exeption "UnReachable IO Exeption" in my code. Again Im really sorry if this wasted your time but will lovee it if you can help me! Thanks! And tell me if there are any other errors i have to be aware of thanks! (BTW i want the error to come!)

import java.io.IOException;


public class Examples1 {

    /**
     * @param args
     */
    public static void main(String[] args)  {
        // TODO Auto-generated method stub

                int[] myNums = {1,2,3};


                try{
                for(int i=0; i<=4;i++){
                    System.out.println(myNums[i]);

                }   
                } catch(IOException e){
                    System.err.println("IndexOutOfBoundsException: " + e.getMessage());
                }



    }

}

1 Answers1

0

You get a compile time error on your catch block, because IOException is a checked exception, for which it can be determined at compile time whether it can occur or not. And in this code it can not occur, so you cannot catch it.

You probably meant to catch the IndexOutOfBoundsException, which is an unchecked exception, so you are not required to catch it. In general, you it is a bad practice to catch unchecked exceptions, but sometimes there may be no other good solution.

wvdz
  • 16,251
  • 4
  • 53
  • 90
  • what is meant by putting `final` keyword inside catch e.g. `catch(final IOException e)` – Rudra Feb 23 '16 at 11:46
  • Got the answer at [link](http://stackoverflow.com/questions/3516816/java-meaning-of-catch-final-someexception-e) – Rudra Feb 23 '16 at 13:07