Multiple exception handlers for file handling

I think my brain is getting raw. Can someone explain that this is the best way to achieve the next task?

I want to open a file, do something with it, and then close it. I want to make sure that the file is definitely closed under any circumstances. I also want to trigger a specific I / O action if the file does not open (does not exist, access is denied, etc.)

For cleaning, I apparently want a bracket , and for handling open failure, I presumably want some kind of try option. But I cannot decide how best to combine them so that they do the right thing without leaving “gaps” (places where an exception at the wrong time could break the material).

+4
source share
2 answers

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).

+3
source
+1
source

Source: https://habr.com/ru/post/1486389/


All Articles