简体   繁体   English

如何在Haskell中定义自定义异常?

[英]How to define a custom exception in Haskell?

The Control.Exception documentation says I can do the following to create my own exception: Control.Exception文档说我可以执行以下操作来创建自己的异常:

 data MyException = ThisException | ThatException
     deriving (Show, Typeable)

 instance Exception MyException

If I paste this into a file and compile (after importing Control.Exception and Data.Typeable), I get: 如果我将其粘贴到文件中并进行编译(在导入Control.Exception和Data.Typeable之后),我得到:

exp.hs:6:20:
    Can't make a derived instance of `Typeable MyException'
      (You need -XDeriveDataTypeable to derive an instance for this class)
    In the data type declaration for `MyException'

Must I turn on this extension in order to have user-defined exceptions? 我必须打开此扩展程序才能拥有用户定义的异常吗? If not, someone please provide an example. 如果没有,请有人举个例子。 Thanks. 谢谢。

Yes, you need to turn on that extension. 是的,您需要打开该扩展程序。 It's not a good idea to try to write the Typeable instance by hand because it has some ties to the internals of GHC. 尝试手动编写Typeable实例并不是一个好主意,因为它与GHC的内部有一些联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM