Suppose I have a method def doSomething: String
which can raise a DoSomethingException
if something goes wrong.
If I write Try(doSomething)
, is there a simple way to map the exception without recovering it?
Basically, I want the failure to become a BusinessException
caused by the DoSomethingException
.
I know the code to do this is very simple, but isn't there any built-in operator to do so? It seems a very common operation but I can't find anything in the API.
However, Scala doesn't actually have checked exceptions. When you want to handle exceptions, you use a try{...} catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.
Scala provides try and catch block to handle exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need.
Try was introduced in Scala 2.10 and behaves as a mappable Either without having to select right or left. You can see how, instead of using explicit try and catch to treat exceptions, Try is used to encapsulate the operation which is always an instance of either Success or Failure.
With recover:
val c = scala.util.Try(doSomething).recover {
case e: DoSomethingException => throw new BusinessException
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With