Use PrivilegedExceptionAction to re-throw any exception privileged code may throw

Also moved the code that tries to run the closure into a method to make
the write method read better.