[英]Scala/Java Error handling a NullPointerException
我正在研究一種從雙鏈接雙端隊列中獲取元素的方法。 當鏈表是空的時候,我得到一個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!!!
}
}
}
謝謝!
如果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)
當列表為空時,您不會采用nullpointerexception。 當你的對象沒有被初始化時你會接受它。 確保您調用“已初始化”的空對象或最佳,也可以在您的方法中預見到
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.