Search code examples
exceptionhaskellthrow

How to throw an exception and exit the program in Haskell?


I have a question: how do I throw an exception and exit the program? I have writen down a simple example:

-- main.hs
import Test

main = do
    Test.foo ""
    putStrLn "make some other things"

Here is the module:

moldule Test where

foo :: String -> IO ()
foo x = do
    if null x
    then THROW EXCEPTION AND EXIT MAIN else putStrLn "okay"

I want to start this and throw a exception and exit the program, but how?


Solution

  • Well, you could try

    foo :: String -> IO ()
    foo x = do
        if null x
        then error "Oops!" else putStrLn "okay"
    

    Or, if you intend to catch the error eventually, then

    import Control.Exception
    data MyException = ThisException | ThatException
       deriving (Show, Typeable)
    
    instance Exception MyException
    
    ...
    
    foo :: String -> IO ()
    foo x = do
        if null x
        then throw ThisException else putStrLn "okay"
    

    There are often more haskelly mechanisms that you could use, such as returning values packed in Maybe type or some other structure that describes the failure. Exceptions seem to fit better in cases where returning complicated types would complicate otherwise re-usable interfaces too much.