【问题标题】:Scala/Java Error handling a NullPointerException处理 NullPointerException 的 Scala/Java 错误
【发布时间】:2014-03-28 12:54:17
【问题描述】:

我正在研究一种从双链接双端队列中获取元素的方法。当linkedlist 为空时,我得到一个nullpointerexception,我试图弄清楚如何处理它。我正在使用以下代码,但它仍然需要我返回 A。有什么想法可以进行此编译吗?

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!!!
    }
  }
}

谢谢!

【问题讨论】:

  • 从 catch 块中返回 null
  • 我试过了,但它给了我一个类型不匹配
  • 是原始类型的双端队列中的数据还是对象?
  • 类 LinkedDeQue[A] 扩展 Deque[A]

标签: java scala error-handling nullpointerexception try-catch


【解决方案1】:

如果last 是一些var,在某些时候最终是null,那么简单的 if 怎么样:

def peekBack(): A = {
  if (last == null) 
    throw new NoSuchElementException("empty list")
  else last.data
}

编辑:如果您确实想返回null,您需要证明A 可以为空:

def peekBack()(implicit ev: Null <:< A): A = {
  if (last == null) ev(null)
  else last.data
}

当然,正确的方法是返回Option[A]

def peekBack(): Option[A] = Option(last).map(_.data)

【讨论】:

    【解决方案2】:

    当您的列表为空时,您不会接受 nullpointerexception。当您的对象未初始化时,您将使用它。确保您调用“已初始化”的空对象或最好的方法,在您的方法中也预见到这一点

    【讨论】:

    • 当 last = null 时我的列表为空。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2015-11-24
    • 2014-01-15
    • 1970-01-01
    • 2015-12-28
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多