Dealing with Asynchronous Exceptions during Resource Acquisition
Posted on August 28, 2014Consider the following code: we open a socket, compute with it, and finally close the socket again. The computation happens inside an exception handler (try), so even when an exception happens we still close the socket:
example1 :: (Socket -> IO a) -> IO a
= do -- WRONG
example1 compute <- openSocket
s <- try $ compute s
r
closeSocket scase r of
Left ex -> throwIO (ex :: SomeException)
Right a -> return a
Although this code correctly deals with synchronous exceptions–exceptions that are the direct result of the execution of the program–it does not deal correctly with asynchronous exceptions–exceptions that are raised as the result of an external event, such as a signal from another thread.