Absolutely forcing an error in Haskell

I use the hs-excelx library, which itself uses a zip archive. The zip archive reaches the condition in which it calls fail, which in this particular context evaluates the call error. This is a call errorin pure code.

I am trying to determine if a particular file is actually an Excel file. I really need to detect this without crashing, so I wrote an isExcel function to detect:

import qualified Data.Excelx as E

isExcel :: BS.ByteString -> Bool
isExcel = maybe False (\_ -> True) . E.toExcelx

Now the trick is that this is a simple formality. If you call E.toExcelx on a byte string that is not a zip archive, the zip archive will simply output error.

But I know what I call isExcelin IO code, so I wrote an I / O function to try to catch the error as follows:

import qualified Data.ByteString.Lazy as BS
import Control.Exception

sd :: BS.ByteString -> IO Bool
sd bs = handle handler $ do
        ie <- return $ Excel.isExcel bs
        return (ie `seq` ie)
    where
    handler :: SomeException -> IO Bool
    handler e = return False

> sd BS.empty
*** Exception: too few bytes. Failed reading at byte position 4

? , http://www.haskell.org/haskellwiki/Error_vs._Exception , . ie Bool, seq ie, , - ? , , , ? zip-.

+3
1

. -, IO, Control.Exception.evaluate. evaluate :: a -> IO a, , . - .

- , . handle, Control.Exception.try, try :: Exception e => IO a -> IO (Either e a), , . , , , , try , . , , ( ), try .

error ErrorCall,

sd :: BS.ByteString -> IO Bool
sd bs = do
        ie <- try $ evaluate $ Excel.isExcel bs
        either (const False) (id) (ie :: Either ErrorCall Bool)

, , isExcel True. toExcel either, .

,

a `seq` a

a. , " , () a, () a ". , . evaluate.

+7

All Articles