读取ghci中的无效整数

时间:2017-03-22 02:06:13

标签: haskell

我尝试了以下操作并且效果很好。

ghci> read "1232" :: Int
1232

以下内容当然无效,但错误信息并不直观。

ghci> read "12 32" :: Int
Stopped in <exception thrown>, <unknown>
_exception :: e = _
Unable to list source for <unknown>
Try rerunning with :trace, :back then :list
ghci> _exception

<interactive>:21:1: error:
    ? No instance for (Show e) arising from a use of ‘print’
      Cannot resolve unknown runtime type ‘e’
      Use :print or :force to determine these types
      Relevant bindings include it :: e (bound at <interactive>:21:1)
      These potential instances exist:
        instance (Show b, Show a) => Show (Either a b)
          -- Defined in ‘Data.Either’
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        ...plus 23 others
        ...plus 28 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    ? In a stmt of an interactive GHCi command: print it

我预计它会产生类似运行时错误的结果,但我不知道它是如何驱动它的。这个例外有什么逻辑吗?

1 个答案:

答案 0 :(得分:1)

除非您想要-fbreak-on-exception or -fbreak-on-error您的计划,否则请勿使用debug运行GHCi。在这种情况下,您可以继续:continue

$ /opt/ghc/8.0.2/bin/ghci -fbreak-on-error                                                                                                                                       
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help

Prelude> read "12 32" :: Int
Stopped in <exception thrown>, <unknown>
_exception :: e = _

[<unknown>] Prelude> :continue
*** Exception: Prelude.read: no parse

请注意,如果使用continue,单个-fbreak-on-exception可能就不够了,因为异常往往会被重新抛出,并且您必须处理每个异常:

$ /opt/ghc/8.0.2/bin/ghci -fbreak-on-exception                                                                                                                                   
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help

Prelude> read "12 32" :: Int
Stopped in <exception thrown>, <unknown>
_exception :: e = _

[<unknown>] Prelude> :continue
Stopped in <exception thrown>, <unknown>
_exception :: e = _

[<unknown>] Prelude> :continue
Stopped in <exception thrown>, <unknown>
_exception :: e = _

[<unknown>] Prelude> :continue
*** Exception: Prelude.read: no parse

顺便说一下,如果没有break-on-X,我们会立即显示异常:

$ /opt/ghc/8.0.2/bin/ghci -fno-break-on-exception -fno-break-on-error                                                                                                                                   
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help

Prelude> read "12 32" :: Int
*** Exception: Prelude.read: no parse

另请注意,实际输出和行为取决于您的GHC和其他标志。