1

I would like to Rewrite the getContents method below to incorporate exception handling. In particular, when an ArrayIndexOutOfBoundsException is generated, the method should return the value -1.0

public class Four
{
 private double [] numbers = {1.0, 2.0, 3.0, 4.0};

 public double getContents(int index)
 {
 return numbers[index];
 }
}

3 Answers 3

3
public class Four
{
    private double [] numbers = {1.0, 2.0, 3.0, 4.0};

    public double getContents(int index)
    {
       try
       {
          return numbers[index];
       }
       catch(ArrayIndexOutOfBoundsException e)
       {
          return -1.0;
       }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3
try {
    return numbers[index] ;
}
catch(ArrayIndexOutOfBoundsException exception) {
    return -1;
}

Comments

0

you could do it this way

public double getContents(int index)
 {
  try {
   return numbers[index];
  } catch (ArrayIndexOutOfBoundsException e){
   return -1.0;
  }
 }

otherwise you could just check if the index is larger than the size of your array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.