Is there a better way to ensure resources are properly released – a better way to write the following code ?
val out: Option[FileOutputStream] = try {
Option(new FileOutputStream(path))
} catch {
case _ => None
}
if (out.isDefined) {
try {
Iterator.continually(in.read).takeWhile(-1 != _).foreach(out.get.write)
} catch {
case e => println(e.getMessage)
} finally {
in.close
out.get.flush()
out.get.close()
}
}
Something like that is a good idea, but I’d make it a method:
(note that we only catch once; if you really want a message printed in one case and not the other, then you do have to catch both like you did). (Also note that I only catch exceptions; catching
Erroralso is usually unwise, since it’s almost impossible to recover from.) The method is used like so:Since it returns a value, you’ll get a
Some(())if it succeeded here (which you can ignore).Edit: to make it more general, I’d really have it return an
Eitherinstead, so you get the exception. Like so:Now if you get a
Right, all went okay. If you get aLeft, you can pick out your exception. If you don’t care about the exception, you can use.right.toOptionto map it into an option, or just use.right.mapor whatever to operate on the correct result only if it is there (just like withOption). (Pattern matching is a useful way to deal withEithers.)