Improved exception handling

As rightfold pointed out `doWithWindow` didn't release the window
resource if `action` caused an exception to be thrown. That has been
fixed.