Consider the following problem.
I am writing wrapper for some string functions; one of them being chr
(for example) from Data.Char
. Now, if the input to my API is a bad input, I want to throw an error otherwise, I simply want to return the integer output. I want to keep the algorithm simple —
getChr someInput = do
x <- chr someInput -- this doesn't evaluate unless we evaluate ourselves
-- handle exception here
result = <_some_evaluation_>
case result of
Left _ -> custom error throw
Right _ -> return something
This is obviously not any Haskell code but a description of what I want the algorithm to look like. I have seen the try (evaluate _)
examples but those return IO (Either SomeException a)
type values that I am unsure can be dealt with simple case statements. I want something very simple so I can case it according to my needs. Is there a way?
try
works well for this.
getChr someInput = do
x <- chr someInput
result = try (some_evaluation x)
case result of
Left (SomeException _) -> print "Oh no!"
Right val -> print val
I guess that your problem might be that you want to catch only some specific exception, right? Then you need to make sure that you cast your the exception somewhere so that it's type is something more special than SomeException
. For example:
do
result <- try something
case result of
Left e -> print (e :: IOException)
Right x -> return x
Or if you want to discard the exception, cast it within const
:
do
result <- try something
case result of
Left e -> const (print "whatever") (e :: IOException)
Right x -> return x
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.