簡體   English   中英

有沒有辦法在Haskell中獲取異常類型?

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

讓我們做出以下假設:

  • 我的程序因未捕獲的異常而中止
  • 我不知道該異常的類型是什么
  • 打印的錯誤消息不包含異常類型的提示

我如何找出該例外的類型?

最小的例子:

main = error "foo"

(這里當然是ErrorCall ,但你無法從錯誤信息中得知。)

是。 假設您使用新的異常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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM