简体   繁体   中英

How to define a custom exception in Haskell?

The Control.Exception documentation says I can do the following to create my own 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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