這里我們轉(zhuǎn)載 Twitter 的 Scala 課堂 ,轉(zhuǎn)載的內(nèi)容基本來自 Twitter 的 Scala 課堂中文翻譯,部分有小改動(dòng).
Scala 中的異??梢栽?try-catch-finally 語法中通過模式匹配使用。
try {
remoteCalculatorService.add(1, 2)
} catch {
case e: ServerIsDownException => log.error(e, "the remote calculator service is unavailable. should have kept your trusty HP.")
} finally {
remoteCalculatorService.close()
}
try 也是面向表達(dá)式的
val result: Int = try {
remoteCalculatorService.add(1, 2)
} catch {
case e: ServerIsDownException => {
log.error(e, "the remote calculator service is unavailable. should have kept your trusty HP.")
0
}
} finally {
remoteCalculatorService.close()
}
這并不是一個(gè)完美編程風(fēng)格的展示,而只是一個(gè)例子,用來說明 try-catch-finally 和 Scala 中其他大部分事物一樣是表達(dá)式。
當(dāng)一個(gè)異常被捕獲處理了,finally 塊將被調(diào)用;它不是表達(dá)式的一部分。