user1766888
user1766888

Reputation: 409

throw an exception on a method call

How do I throw and UnsupportedOperationException on a method? So if I have an Iterable object and I'm trying to disallow the remove method for that object.

In the method below I'm returning an iterable object whose iterator's remove I need to disable by throwing an UnsupportedErrorException. Can I do this within the body of the method or how so?

  public Iterable<String> getInNodes (String destinationNodeName)  {
  if (!hasNode(destinationNodeName))
      return emptySetOfString;
  else {
  for(String e : nodeMap.get(destinationNodeName).inNodes)
  {
      emptySetOfString.add(e);
  }
  return emptySetOfString;
  }
}

Upvotes: 3

Views: 174

Answers (4)

Cory Kendall
Cory Kendall

Reputation: 7324

I may have misunderstood your question.

If you have a normal Iterable, and you want to convert it to an Iterable that generates iterators on which remove can not be called, you can use this monstrosity made possible by anonymous subclassing:

Iterable<String> iterable = // normal Iterable<String> you already have...

Iterable<String> noRemoveIteratorGeneratingIterable = new Iterable<String>() {
    @Override        
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            Iterator<String> internalIterator = iterable.iterator();

            @Override
            public boolean hasNext() {
                return internalIterator.hasNext();
            }

            @Override
            public String next() {
                return internalIterator.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Nope!");
            }
        };
    }
};

Upvotes: 2

Yogendra Singh
Yogendra Singh

Reputation: 34387

You can try throwing the message with appropriate message as well:

public void remove() {
   throw new UnsupportedOperationException("Remove is unsupported on this object");
}

Upvotes: 0

sge
sge

Reputation: 7650

In your class you can just @Override the original method

public class myIterable extends Iterable {
    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Then create Objects of this class instead of original Iterable.

Upvotes: 0

tjg184
tjg184

Reputation: 4686

Try this.

@Override
public void remove() {
   throw new UnsupportedOperationException();
}

Upvotes: 5

Related Questions