I need to initialise a set of vals, where the code to initialise them might throw an exception. I’d love to write:
try {
val x = ... generate x value ...
val y = ... generate y value ...
} catch { ... exception handling ... }
... use x and y ...
But this (obviously) doesn’t work because x and y aren’t in scope outside of the try.
It’s easy to solve the problem by using mutable variables:
var x: Whatever = _
var y: Whatever = _
try {
x = ... generate x value ...
y = ... generate y value ...
} catch { ... exception handling ... }
... use x and y ...
But that’s not exactly very nice.
It’s also easy to solve the problem by duplicating the exception handling:
val x = try { ... generate x value ... } catch { ... exception handling ... }
val y = try { ... generate y value ... } catch { ... exception handling ... }
... use x and y ...
But that involves duplicating the exception handling.
There must be a “nice” way, but it’s eluding me.
A straightforward solution would be to define a wrapper function that uses by-name parameters.
Or, if you’re feeling really swanky, Scala 2.9 allows a partial function to be used as the exception handler.
On the whole, I would say that the first method is the most straightforward. But if you can write reusable bits of exception handlers that can be composed together using
orElseorandThen, then the second method would be more appropriate.