[Haskell-cafe] Exceptions

Don Stewart dons at galois.com
Sun Jul 27 15:22:09 EDT 2008


aneumann:
> Hello,
> 
> I think it'd be nice if the compiler could warn me if there are any  
> exceptions which I'm not catching, similar to checked exceptions in  
> Java. Does anyone know of a possibility to do that in Haskell?
> 
> Adrian

You could provide exception-safe wrappers for the functions you use,
that catch any exception and flatten it to an Either type (or something
similar). Then GHC's usual coverage checking will enforce the handling.


    import qualified System.IO
    import Control.Exception

    maybeReadFile :: FilePath -> IO (Maybe String)
    maybeReadFile f = handle (\_ -> return Nothing)
                             (Just `fmap` System.IO.readFile f)

    {-
    *A> maybeReadFile "/tmp/DOESNOTEXIST"
    Nothing
    -}

    main = do
        mf <- maybeReadFile "DOESNOTEXIST"
        case mf of
             Nothing -> return ()
             Just s  -> print s


The ability to control exceptions seems like something we should have more solutions for.

-- Don


More information about the Haskell-Cafe mailing list