Scala/Java Error handling a NullPointerException
error-handling, java, nullpointerexception, scala, try-catch
Solution
If `last` is some `var` that ends up being `null` at some point, what about a simple if:
def peekBack(): A = {
if (last == null)
throw new NoSuchElementException("empty list")
else last.data
}
Edit: if you do want to return `null`, you need a proof that `A` is nullable:
def peekBack()(implicit ev: Null <:< A): A = {
if (last == null) ev(null)
else last.data
}
Of course the proper way to do this would be to return an `Option[A]`:
def peekBack(): Option[A] = Option(last).map(_.data)
Problem
I am working on a method which gets elements out of a double linked deque. When the linkedlist is empty, I get a nullpointerexception and I am trying to figure out how to handle it. I am using to following code but it still requires me to return A. Any ideas how I can get to this compile? ``` def peekBack():A = { try { last.data // return if the list is full if not, catch the nullpointerexception } catch { case ex: NullPointerException => { println("There are no elements in this list.") //Error is here, it is requiring me to return something!!! } } } ``` Thanks!