Prelude.catch Re: Proposal: System.Environment.getEnv should return Maybe

Christian Maeder Christian.Maeder at
Thu Feb 23 09:17:00 CET 2012

Am 23.02.2012 01:07, schrieb Evan Laforge:
> On Wed, Feb 22, 2012 at 3:51 PM, John Meacham<john at>  wrote:
>> On Wed, Feb 22, 2012 at 3:05 PM, Evan Laforge<qdunkan at>  wrote:
>>> It's awkward and surprising how getEnv throws an exception when an env
>>> var is not set, since it's very common for env vars to be optional,
>>> and it's not convenient to catch exceptions in haskell (I have to look
>>> up Control.Exception every time, and then add LANGUAGE
>> For true IO exceptions, you should be using the Prelude.catch mechanism.
>> It's the right thing to do and makes your program more portable as a bonus.
>> It is quite unfortunate that IO exceptions became conflated with imprecise
>> and dynamic exceptions and clash in their names. They really are different
>> beasts alltogether.
> Good point, I had forgotten about the Prelude catch.  I think I can go
> remove a bunch of ScopedTypedVariables now.

This situation is particularly annoying since hlint (1.8.24) always says:
... Error: Use Control.Exception.catch
Why not:
Note: Prelude.catch does not catch most exceptions

And now I learn that Prelude.catch is the right version for i.e. file IO 
(so I should probably switch off that hlint "Error").

Regarding the actual proposal, I fully agree. I always use a wrapper 
based on getEnvironment.

getEnvSave :: a                   -- ^ default value
            -> String              -- ^ name of environment variable
            -> (String -> Maybe a) -- ^ parse and check value
            -> IO a
getEnvSave defValue envVar readFun =
     liftM (maybe defValue (fromMaybe defValue . readFun)
            . lookup envVar) getEnvironment

Cheers Christian

> The ghc exception situation is a bit messy, and I never have all the
> distinctions quite memorized, but it's also because I hardly ever have
> to deal with exceptions (of the "magical return value" variety, I use
> Either and Maybe all the time), unlike certain other languages.  And
> that's a very good thing!
> If I forget the rest about exceptions due to lack of use, I should at
> least remember that IO exceptions are different from, and better
> behaved than, the imprecise ones.

More information about the Libraries mailing list