Does anybody have good examples of using scala.util.control.Exception
version 2.12.0 (version 2.8.0), ? I am struggling to figure it out from the types.
try/catch/finally A basic way we can handle exceptions in Scala is the try/catch/finally construct, really similar to the Java one. In the following example, to make testing easier, we'll return a different negative error code for each exception caught: def tryCatch(a: Int, b: Int): Int = { try { return Calculator.
The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util.
Is it required to catch checked exceptions in Scala? One difference from Java that you'll quickly notice in Scala is that unlike Java, Scala does not require you to catch checked exceptions, or declare them in a throws clause.
Indeed - I also find it pretty confusing! Here's a problem where I have some property which may be a parseable date:
def parse(s: String) : Date = new SimpleDateFormat("yyyy-MM-dd").parse(s) def parseDate = parse(System.getProperty("foo.bar")) type PE = ParseException import scala.util.control.Exception._ val d1 = try { parseDate } catch { case e: PE => new Date }
Switching this to a functional form:
val date = catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) )
In the above code, turns catching(t) either expr
will result in an Either[T, E]
where T
is the throwable's type and E
is the expression's type. This can then be converted to a specific value via a fold
.
Or another version again:
val date = handling(classOf[PE]) by (_ => new Date) apply parseDate
This is perhaps a little clearer - the following are equivalent:
handling(t) by g apply f try { f } catch { case _ : t => g }
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