Dmitriy
Dmitriy

Reputation: 173

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!

Upvotes: 7

Views: 722

Answers (2)

Randall Schulz
Randall Schulz

Reputation: 26486

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 }
}

Upvotes: 6

Jackson Davis
Jackson Davis

Reputation: 3401

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.

Upvotes: 11

Related Questions