Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scala.util.control.Exception

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.

like image 993
Alexey Romanov Avatar asked May 25 '10 09:05

Alexey Romanov


People also ask

How to handle the exception in Scala?

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.

Which Scala type may throw an exception or a successfully computed value and is commonly used to trap and propagate errors?

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 exception in Scala?

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.


1 Answers

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 } 
like image 198
oxbow_lakes Avatar answered Oct 04 '22 05:10

oxbow_lakes