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