1

I have a problem trying to use the try/catch in my code. Whenever i try and return the result; i get the error "cannot resolve symbol 'result'". Here is my code.

public Object remove(int index) {
    try{
        Object result = this.get(index);
        for (int k = index; k < size-1; k++) items[k] = items[k + 1];
        items[size] = null;
        size--;
        return result;
     }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Exception occurred in 'remove' method.");
        return result;
    }
}
codiacTushki
  • 750
  • 1
  • 9
  • 22
Volken
  • 255
  • 1
  • 4
  • 23

2 Answers2

1

You have defined result variable within try block. if you declare variable within {} braces then that variable will be avialble for use within those braces only and it wont be available to outside world.

So to resolve the issue, you do something like:

Object result = null;
try {
   ....
} catch ... {
}
return result;
SMA
  • 36,381
  • 8
  • 49
  • 73
0

result is initialized inside the try block. The try/catch blocks work similarly to if/else in that you can not see an object initialized in the other block. You can work around this by initializing result before the try.

public Object remove(int index) {
  Object result;
  try{
    result = this.get(index);
    for (int k = index; k < size-1; k++) items[k] = items[k + 1];
    items[size] = null;
    size--;
    return result;
  }
  catch(ArrayIndexOutOfBoundsException e){
    System.out.println("Exception occurred in 'remove' method.");
    return result;
  }
}

You probably shouldn't have to catch the out of bounds exception at all how ever. Asuming items is an array, you can use items.length in your for loop to prever going out of bounds.

mjuopperi
  • 773
  • 7
  • 25