excption via custom control

Posted satyrs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于excption via custom control的主要内容,如果未能解决你的问题,请参考以下文章

使用via或viaTable关系从关系生成mysql查询

初学android开发,求教怎么看log。 是以前的测试测出来的一个小问题,然后给了log。 我该怎么看。。。

MooTools自定义事件

MAC版AE插件怎么安装到扩展里

我如何使单选按钮设置成角度

带有数字变量的`对比度<-`(`*tmp*`,value = contr.funs[1 + isOF[nn]])中的错误[重复]