有没有办法在Haskell中获取异常类型?

时间:2012-03-21 06:40:12

标签: haskell

让我们做出以下假设:

  • 我的程序因未捕获的异常而中止
  • 我不知道该例外的类型是什么
  • 打印的错误消息不包含异常类型
  • 的提示

我如何找出该例外的类型?

最小例子:

main = error "foo"

(这里当然是ErrorCall,但您无法从错误消息中得知。)

1 个答案:

答案 0 :(得分:17)

是。假设您使用新的例外API,所有Exception类型必须是Typeable的实例。

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

结果:

Caught exception of type GHC.Exception.ErrorCall
example