0

I'm having some trouble understanding the implications of the code in my accessor method below. Eclipse's compiler is requiring that I have a return statement after my try-catch block. Does this mean that my getter method will always return null or will it return the item I'm trying to retrieve if it int i doesn't need to be caught by the IndexOutOfBoundsException?

public T get(int i)
{
    try
    {
        return bag[i];
    }
    catch(IndexOutOfBoundsException e) //if(logiSize < i+1)
    {
        System.out.println("Collection has fewer items than the index you entered!");
        System.out.println("Returning null"); //or should I...?
    }
    return null;
}

Can anyone help me understand the implications here? Thanks so much!

Her
  • 55
  • 1
  • 9
  • If an IOOBE occurs and the catch block is entered, **nothing** is returned, and that's not kosher. So either return from the catch block, or after it. – Hovercraft Full Of Eels Jan 29 '16 at 02:36
  • In "real code", though, this is a case where it would be perfectly fine to just *let the exception happen* and bubble to the caller. From `List`: "`IndexOutOfBoundsException` - if the index is out of range (index < 0 || index >= size())" – chrylis -cautiouslyoptimistic- Jan 29 '16 at 02:49
  • @HovercraftFullOfEels okay so that's a general rule of thumb to make sure that something is returned incase what was tried doesn't work/isn't executed, right? – Her Jan 29 '16 at 03:26

1 Answers1

2

Your method will return bag[i] unless you have an IndexOutOfBoundsException exception executing the return statement. In that case, they exception is caught, and since you're not throwing another exception inside the catch black. The method will proceed to return null.

If you only need to check for bounds, you could do this:

public T get(int i, T[] bag) {
    if(i < bag.length) {
        return bag[i];
    }
    return null;
}
Ulises
  • 9,115
  • 2
  • 30
  • 27
  • Oh wow! Okay, thanks so much! So I guess I don't really need to use a try-catch block in this case... I'm required to for this particular implementation though. But I'm glad to know there's more than one way to do this. :) – Her Jan 29 '16 at 03:18