[英]Handling Haskell exceptions with a single case clause?
考慮以下問題。
我正在為一些字符串函數編寫包裝器; 其中之一是來自Data.Char
chr
(例如)。 現在,如果我的API輸入是錯誤的輸入,那么我想拋出一個錯誤,否則,我只想返回整數輸出。 我想保持算法簡單-
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
這顯然不是任何Haskell代碼,而是對我希望算法看起來像的描述。 我已經看過try (evaluate _)
示例,但是那些我不確定的返回IO (Either SomeException a)
類型值可以用簡單的case語句處理。 我想要一些非常簡單的東西,因此我可以根據自己的需要進行整理。 有辦法嗎?
try
為此工作很好。
getChr someInput = do
x <- chr someInput
result = try (some_evaluation x)
case result of
Left (SomeException _) -> print "Oh no!"
Right val -> print val
我想您的問題可能是您只想捕獲某些特定的異常,對吧? 然后,您需要確保將異常SomeException
到某個地方,以便其類型比SomeException
更特殊。 例如:
do
result <- try something
case result of
Left e -> print (e :: IOException)
Right x -> return x
或者,如果您想丟棄該異常,則將其const
:
do
result <- try something
case result of
Left e -> const (print "whatever") (e :: IOException)
Right x -> return x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.