标签:href reading 声明 fun first something addition not why
scala> import scala.util.control.Exception._ import scala.util.control.Exception._ scala> val numberFormat = catching(classOf[NumberFormatException]) numberFormat: util.control.Exception.Catch[Nothing] = Catch(java.lang.NumberFormatException) scala> val result = numberFormat opt { "10".toInt } result: Option[Int] = Some(10) scala> result match { | case Some(n) => // do something | case None => // handle this situation |
(The other reason (and the one more pertinent to Java developers), is that it provides a nice way to handle common exceptions. Why do I say nice? First it declares when exceptions are handled before the code and that provides more context while reading the code. In addition, if you create the Catch object and assign it to a nicely named variable then it is clear what the intent is. For example there may be several reasons to catch a runtime exception and they should be handled differently. A few well-named variables can really assist in readability. A final point is that several of these variables can be defined in on object and shared throughout a project adding some consistency to a project.)(真实是好习惯。)
scala> def catching[T](exceptions: Class[_]*)(body: => T) = {
| try {
| Some (body)
| } catch {
| case e if (exceptions contains e.getClass) => None
| }
| }
catching: [T](exceptions: Class[_]*)(body: => T)Option[T]
catching在没有异常发生返回Some(...)或发生声明的异常时返回None或非声明异常发生时throw
REFERENCE http://daily-scala.blogspot.com/2009/11/defining-custom-control-structures.html
标签:href reading 声明 fun first something addition not why
原文地址:http://www.cnblogs.com/yumanman/p/7634931.html