Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Can't catch exception thrown inside a closure

Disclaimer: absolute novice in Scala :(

I have the following defined:

def tryAndReport(body: Unit) : Unit = {
  try {
    body
  } catch {
    case e: MySpecificException => doSomethingUseful
  }
}

I call it like this:

tryAndReport{
  someCodeThatThrowsMySpecificException()
}

While the call to someCodeThatThrowsMySpecificException happens just fine, the exception is not being caught in tryAndReport.

Why?

Thank you!

like image 427
Dmitriy Avatar asked Apr 17 '10 03:04

Dmitriy


2 Answers

Try changing body from Unit to => Unit. The way its defined now, it considers body a block of code to evaluate to Unit. Using call-by-name, it will be executed in the try as defined and should be caught.

like image 189
Jackson Davis Avatar answered Oct 19 '22 15:10

Jackson Davis


The body in your tryAndReport method is not a closure or block, it's a value (of type Unit).

I don't recommend using a by-name argument, but rather an explicit function.

def tryAndReport(block: () => Unit): Unit = {
  try { block() }
  catch { case e: MSE => dSU }
}
like image 28
Randall Schulz Avatar answered Oct 19 '22 14:10

Randall Schulz