I'm just wondering if there is any generic exception that I can throw in case I don't want to create custom one for example in some simple scripts.
I'm looking for an exception that takes a single String
as a reason.
As an example the NoMethodError
, however it has a specific semantics and I want a generic one.
https://hackage.haskell.org/package/base-4.16.0.0/docs/Control-Exception.html#t:NoMethodError
CodePudding user response:
It depends on exactly what you want to do.
If you want to throw an IO error then you can just call error
, which generates an ErrorCall
exception. You can optionally catch that in your main
function and produce a more user-friendly error message. This is roughly equivalent to what most other programming languages provide in the way of exception handling.
If you have some non-IO computations which might fail at various stages (e.g. looking something up in a Map
and not finding it) then you can use Either String
as a quick-and-dirty exception monad. The equivalent of throwing an exception is Left
.
To make Either String
a bit more powerful you can import Control.Monad.Except
. This introduces the MonadError
typeclass, which includes Either
as an instance. Hence by importing it you can use throwError
and catchError
.
Alternatively you can use the ExceptT
monad transformer (also part of Control.Monad.Except
) to add exceptions to any other monad you happen to be working with.