Reputation: 459
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.
Upvotes: 1
Views: 229
Reputation: 139038
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.
Upvotes: 3