Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the type of an exception in Haskell?

Tags:

haskell

Let's make the following assumptions:

  • my program aborts due to an uncaught exception
  • I have no idea what the type of that exception is
  • the printed error message contains no hint on the exception type

How would I find out the type of that exception?

Minimal example:

main = error "foo"

(Here it's of course ErrorCall, but you can't tell from the error message.)

like image 841
user1078763 Avatar asked Mar 21 '12 06:03

user1078763


People also ask

Does Haskell have exception handling?

The Haskell runtime system allows any IO action to throw runtime exceptions. Many common library functions throw runtime exceptions. There is no indication at the type level if something throws an exception. You should assume that, unless explicitly documented otherwise, all actions may throw an exception.

How do you use try in Haskell?

try :: Exception e => IO a -> IO (Either e a) try takes an IO action to run, and returns an Either . If the computation succeeded, the result is given wrapped in a Right constructor. (Think right as opposed to wrong). If the action threw an exception of the specified type, it is returned in a Left constructor.


1 Answers

Yes. All Exception types must be instances of Typeable, assuming you use the new exceptions API.

import Control.Exception
import Data.Typeable
import Prelude hiding (catch)

realMain = error "example"
main = realMain `catch` h where
  h (SomeException e) = do
    putStrLn $ "Caught exception of type " ++ show (typeOf e)
    putStrLn $ show e

Results:

Caught exception of type GHC.Exception.ErrorCall
example
like image 80
Dietrich Epp Avatar answered Sep 28 '22 04:09

Dietrich Epp