views:

113

answers:

2

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!

+9  A: 

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.

Jackson Davis
+5  A: 

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 }
}
Randall Schulz
*I don't recommend using a by-name argument, but rather an explicit function.* -- Why?
missingfaktor
I second that, you shouldn't give a recommandation like that without a rationale.
David Pierre
Because I believe in saying what you mean. You want the function evaluated within the body of the `tryAndReport`, that should not be hidden behind a by-name parameter.
Randall Schulz