excption via custom control


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]
  1. scala> runtime { "".toInt }                                                                          
  2. res2: Option[java.lang.Number] = None
  3. scala> runtime { "10".toInt }
  4. res3: Option[java.lang.Number] = Some(10)
  5. scala> runtime { throw new NullPointerException }
  6. res6: Option[java.lang.Number] = None
  7. scala> runtime { throw new RuntimeException }
  8. java.lang.RuntimeException
  9.         at $anonfun$1.apply(< console>:10)
  10.         at $anonfun$1.apply(< console>:10)
  11.         at .catching(< console>:9)
  12.         at $anonfun$1.apply(< console>:8)
  13.         at $anonfun$1.apply(< console>:8)
  14.         at .< init>(< console>:10)
  15.         at .< clinit>(< console>)
  16.         at RequestResult$.< init>(< console>:4)
  17.         at RequestResult$.< clinit>(< console>)
  18.         at RequestResult$result(< console>)
  19.         ...

catching在没有异常发生返回Some(...)或发生声明的异常时返回None或非声明异常发生时throw

 

 

REFERENCE http://daily-scala.blogspot.com/2009/11/defining-custom-control-structures.html

posted on 2017-10-07 15:55  satyrs  阅读(144)  评论(0编辑  收藏  举报

导航