Initialising vals which might throw an exception
- by Paul Butcher
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.