Initialising vals which might throw an exception

Posted by Paul Butcher on Stack Overflow See other posts from Stack Overflow or by Paul Butcher
Published on 2011-11-11T23:08:02Z Indexed on 2011/11/12 1:50 UTC
Read the original article Hit count: 252

Filed under:

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.

© Stack Overflow or respective owner

Related posts about scala