educative.io

Educative

Return statement in try catch |why [0] is used here: c.method1()[0]

System.out.print("Returned Value is "+c.method1()[0]);
why [0] is used here: c.method1()[0]

class Parent {

public static void main(String[] args) {

    Child c  =  new Child();

    System.out.print("Returned Value is "+c.method1()[0]);

}

}

class Child{

public int[] method1() {

    int value = 10;

    int[] arr = {1};

    try{

        System.out.println(arr[4]);

    }catch(ArrayIndexOutOfBoundsException e){

        System.out.println("Exception caught value is "+ arr[0]);

        return arr; // value is being returned from inside catch

    }finally{

        arr[0] = 2;

        System.out.println("Finally value is "+ arr[0]);

    }

    return arr; //returning a referential type variable

}

}

Hi @rishabh_verma

It’s set just for the sake of our example, explaining how an exception will occur and at which point. We can set it to [1], or [2] or any value but in that case, we’ll have to initialize the array accordingly as it will get that index value from the array of method1, in case if such index doesn’t exist it’ll throw an exception as Index out of bounds.