[Haskell-cafe] IO and exceptions

Roman Cheplyaka roma at ro-che.info
Sun Nov 9 13:53:25 UTC 2014


On 09/11/14 08:38, Michael Orlitzky wrote:
> On 11/09/2014 08:11 AM, Roman Cheplyaka wrote:
>> Let's say you knew what exceptions could be thrown. What would you do
>> differently then?
>>
>> Typically, if it's a command-line app and something unexpected happens,
>> you simply present the error to the user. That's what exceptions do
>> already without any effort from you.
>>
> 
> The output from the exception is usually useless, though. Rather than,
> 
>   *** Exception: EACCES
> 
> (or something similar, whatever, I'm making it up), I want to show:
> 
>   Insufficient permissions for accessing /run/<app>. This can be fixed
>   by granting write and execute access on that directory to the user
>   under which the application is running.
> 
> If the operation can fail in different ways -- like if the directory is
> missing entirely -- I need to pattern match on the exception and display
> something else.
> 
> Another example: I don't want to log a "read error" in my daemon, which
> is what I'll get if I log the exception. I want to know *what* failed to
> be read. Was it a file (that a cron job deleted) or a network socket
> (whose connection was dropped)? I need to catch those in the code, where
> I know what's being read, and what the "read error" means in context.

Both points are valid.

Re the first, you still can achieve it by pattern-matching on
exceptions. The fact that you don't know the exact set of exceptions
makes it harder, but the truth is, for a non-trivial application, that
set would be huge. Like, let's say you use a database. It brings in all
sorts of network-related exceptions and database-level exceptions.

The way to handle those, as you point out, is to augment them with
high-level information ("Could not retrieve user's data"), and then
maybe attach the low-level exception for debugging purposes. Again, you
don't really need to know the whole set of exceptions in order to do
that. Just wrap your database access function in 'try', and you'll know
that whatever exception was caught, it prevented the retrieval of user's
data (but keep in mind that it might be an asynchronous exception
unrelated to your database activity).

Roman


More information about the Haskell-Cafe mailing list