Exception Handling

Scala encourages a coding style that lessens the need for exceptions and exception handling. But exceptions are still used, especially where Scala interacts with Java code, where use of exceptions is more prevalent.

Unlike Java, Scala does not have checked exceptions, which are now regarded as an unsuccessful design. Java’s checked exceptions are treated as unchecked by Scala. There is also no throws clause on method declarations. However, there is a @throws annotation that is useful for Java interoperability.

Scala treats exception handling as just another pattern match (???), allowing us to implement concise handling of many different kinds of exceptions.

Code Example

// TryCatch.scala
package com.brown

import scala.io.Source
import scala.util.control.NonFatal

/**
  * Created by BrownWong on 2016/10/11.
  */
object TryCatch {
  def main(args: Array[String]) = {
    countLines("haha.txt")
  }

  def countLines(fileName: String) = {
    var source: Option[Source] = None
    try {
      source = Some(Source.fromFile(fileName))
      val size = source.get.getLines.size
      println(s"file $fileName has $size lines")
    } catch{
      case NonFatal(ex) => println(s"Non fatal exception! $ex")
    } finally {
      for (s <- source) {
        println(s"Closing $fileName")
        s.close()
      }
    }
  }
}

haha.txt

nima
niba
niye
ninai
haha
bye
!

output

file haha.txt has 7 lines
Closing haha.txt

Note the catch clause. Scala uses pattern matches to pick the exceptions you want to catch. This is more compact and more flexible than Java’s use of separate catch clauses for each exception. In this case, the clause case NonFatal(ex) => … uses scala.util.control.NonFatal to match any exception that isn’t considered fatal.

This is a widely used idiom; use a for comprehension when you need to test whether an Option is a Some, in which case you do some work, or is a None, in which case you ignore it.


Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值