Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
develhevel Avatar asked May 20 '11 10:05

develhevel


People also ask

How do I exit Haskell?

Our Haskell process uses exitWith to exit the process with exit code 42 . Then echo $? prints the last exit code. All relatively straightforward (if you're familiar with the shell).

Does throwing an exception terminate the program?

We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.


1 Answers

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.

like image 174
aleator Avatar answered Oct 04 '22 01:10

aleator