Added a begin around closing of IOs

On Jruby there seems to be a race condition that causes
$! to be set but no exception thrown. Putting this inside a begin
seems to fix this.