Use try to open the file. If you successfully use finally to work with the file descriptor and then close the file. If the file cannot be opened, go to your case with an error. Therefore, the code should look something like this:
do res <- try (openFile filename mode) case res of Right handle -> finally (workWith handle) (hClose handle) Left (e :: SomeException) -> handleOpeningError e
This will result in the execution of the handleOpeningError action if openFile is unsuccessful and it will close the file descriptor under any circumstances. If an exception occurs during workWith handle , this exception will be re-selected after the file descriptor has been closed (if I understand you correctly, you want to handle the exceptions that openFile throws, otherwise you only want to ensure the file was closed).
source share