简体   繁体   中英

Scala exception handling using try and recover or toOption

This is one handler written to recover from exception handling but when i call it doesn't recover but fails for below error message

def exphandler(i: Any): Try[Any] = Try(i) recover {
  case e => "Hello"
}


exphandler(BigDecimal(Cols(5))/adjust_currency_map(static(4))), //Open price


======================================
java.lang.NumberFormatException
                                              //|   at java.math.BigDecimal.<init>      (BigDecimal.java:459)
                                              //|   at java.math.BigDecimal.<init>(BigDecimal.java:728)
                                              //|   at scala.math.BigDecimal$.exact(BigDecimal.scala:125)
                                              //|   at scala.math.BigDecimal$.apply(BigDecimal.scala:283)
                                              //|   at com.DC.FTDataParser.FileParser$$anonfun$1.apply(FileParser.scala:115)

===============================

Any points will be helpful as it is making me mad.

The argument to exphandler is being evaluated before the exception it throws can be caught by Try . You can fix this by using a by-name parameter :

def exphandler(i: => Any): Try[Any] = Try(i) recover {
  case e => "Hello"
}

Now the argument to exphandler won't be evaluated until inside of the call to Try , where the exception will be caught and represented as you're expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM