The file opening needs to be outside the the try block (if the open itself fails then the close from the finally block will also fail due to trying to close a file that hasn't been opened => the initial exception will be shadowed).