Question

If someone calls my method, I want to defensively deal with the problem. Usually I just return null.

I decided to implement a try catch but it looks like I just end up returning null anyway.

Can I write my try catch in such a way that at the end of method it doesn't return null?

Sample code, using peek on a Stack class.

    public T peek()
    {
        T temp = null;

        try
        {
            temp = array[size]; 
        }

        catch(Exception e)
        {
        }

        return temp;
    }

When called with an empty stack. It will return null.

So should I even bother with the try catch for this kind of case? I am tempted to do this:

if(isEmpty())
   return null;

If the stack is not empty I want to return the element. If the stack is empty then can I avoid returning null if I use the try-catch?

Was it helpful?

Solution

The method has to return something or throw an Exception. If you have an unbounded generic type, then things like null object patterns can't be used, so the options are returning null, returning something that contains T like Optional<T>, or throwing an Exception.

If you don't like the safety of null, you can use Optional, either from Java 8 or a library. Checked exceptions have a similar safety but are inappropriate here.

OTHER TIPS

This is how I would approach the problem. By throwing an exception in the peek function, putting the duty of handling that exception in the caller. Why? Because I want an error to cause an explosion as big as possible. The peek method also became smaller. Also as you already agree on, returning null is lame.

public T peek() throws IndexOutOfBoundsException
{   
  return array[size]; 
}

and

try
{
  T top = thestack.peek();
  /* Do something with that object */
}
catch(IndexOutOfBoundsException e)
{
  /* Do something else */
}

It's hard to imagine the array[size] throwing an Exception, unless array is null or size is outside the length of array. So, you could do something like this -

 if (array != null && array.length > size) {
   return array[size - 1]; // assuming your size starts at 1
 }
 return null; // need to return something, if not null you need an option type.

Edit

Or, using an Option monad - and something like,

 if (array != null && array.length > size) {
   return new Some<T>(array[size - 1]); // assuming your size starts at 1
 }
 return new None<T>(); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top