Wednesday, November 30, 2016

IndexOutOfBoundsException

public class ExceptionDemo{
    public static void main(String[] args){
        int[] array = new int[2];
        try {
            System.out.println(array[100]);//non-existent
        } catch (IndexOutOfBoundsException ex){
            StackTraceElement[] e = ex.getStackTrace();
            System.err.println("Got error= " + ex + "\n"+
                               "in file "+e[0].getFileName() +"\n"+
                               "in class "+e[0].getClassName() +"\n"+
                               "in method "+e[0].getMethodName() +"\n"+
                               "in line "+e[0].getLineNumber());
            System.err.println("Full trace= ");
            ex.printStackTrace(System.err);
        }
        System.out.println("As Salamu Alaikum");
    }
}


Reference:
https://docs.oracle.com/javase/tutorial/essential/exceptions/
http://docs.oracle.com/javase/8/docs/api/java/lang/StackTraceElement.html
http://stackoverflow.com/questions/30437019/include-filename-line-number-corresponding-to-system-out-print-statements-in-ecl

No comments: