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
?
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 containsT
likeOptional<T>
, or throwing an Exception.If you don't like the safety of
null
, you can useOptional
, either from Java 8 or a library. Checked exceptions have a similar safety but are inappropriate here.