Creating a Class that throws IndexOutOfBoundsException


I was wondering if someone can help me create a class that throws an IndexOutOfBoundsException

i.e. like
class ThrowingExcep{
public Object elementAt (int index)throws IndexOutOfBoundsException{
return ___?____   ;}

I do not know what to put in the return statement

Thanks in advance
Who is Participating?
Sasha_MapaConnect With a Mentor Commented:
What you want is a method that throws the exception, not a class (classes don't throw exceptions). The answer is that you don't need a return statement if you are planning to unconditionally throwing an exception. What you would do is simply this:

public Object elementAt(int i){
  throw new IndexOutOfBoundsException(String.valueOf(i));

A more reasonable elementAt method would be this (class code included):

public class Vector{

  private Object [] arr;
  private int size;

  public Object elementAt(int i) throws IndexOutOfBoundsException{
    if ((i<0)||(i>=size))
      throw new IndexOutOfBoundsException(String.valueOf(i));
    return arr[i];


A throw statement passes the control to the next enclosing catch statement - if you have no such statement in the method that throws the exception, the method terminates without returning a value and control is tranferred (recursively up the stack) to the enclosing catch statement of the method that called your method.

Sasha Maryanovsky.
If I understand the intent correctly, the exception would be thrown when something went wrong (and no return would be needed), otherwise you return the relevant Object. So I think it would look something like:

class ThrowingExcep{
{   Vector l;
    int max;

    {   l=new Vector();

    public Object elementAt(int index) throws IndexOutOfBoundsException
    {   if(index>=max)throw new OutOfBoundsException();
import java.util.*;

class StringStore{

     Vector v;

     public StringStore(){
           v = new Vector();

     public void putString(String s){

     public String getString(int index) throws IndexOutOfBoundsException{
          if (index > v.size()){
               throw new IndexOutOfBoundsException();
          return (String)v.elementAt(index);
Woah...everyone posted at once.
Should have reloaded before I hit submit.
willcontAuthor Commented:
Thank you
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.