简体   繁体   English

Haskell异常处理如何工作?

[英]How does Haskell exception handling work?

foldl1 (+) []

如何捕获结果错误?

Pure code may throw asynchronous, imprecise exceptions , for example, when a partial function encounters input it has no case to handle. 纯代码可能会抛出异步的, 不精确的异常 ,例如,当部分函数遇到输入时,它无法处理。

These are logical errors, usually, indicating bugs in the program specification. 这些是逻辑错误,通常表示程序规范中的错误。

They may be caught in IO code (usually at an outer layer of the program), via an exception handler . 它们可能通过异常处理程序被IO代码(通常在程序的外层)捕获。

For example, to catch your missing case for the empty list, 例如,要捕获空列表的遗漏案例,

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns        #-}

import Control.Exception

main = do
    handle (\(e :: SomeException) -> print $ "This program as a bug: " ++ show e) $ do
        let !v = foldl1 (+) ([] :: [Int])
        return ()

We can observe that the exception is caught, and the program terminates. 我们可以观察到异常被捕获,并且程序终止。

$ ./A
"This program as a bug: Prelude.foldl1: empty list"

所有你需要了解的haskell例外 (在一个简单的阅读:)

Purist answer: the result is undefined (specifically, bottom ). 纯粹答案:结果未定义(具体来说, 底部 )。 You can't do anything with it except crash if the value is used in any way to build the program's results. 如果以任何方式使用该值来构建程序的结果,则除了崩溃之外,您无法执行任何操作。 See Haskell 98 Report section 3.1 . 参见Haskell 98 Report 3.1节 It specifies that such "errors cause immediate program termination and cannot be caught by the user." 它指定这样的“错误导致程序立即终止并且不能被用户捕获”。

It's best to check input values and handle them BEFORE they can get this far. 最好检查输入值并在它们可以实现这一目标之前对其进行处理。 Don't use fold1 if the list could have 0 elements. 如果列表可以包含0个元素,请不要使用fold1。

In practice though, you can use the methods in the other answers to catch it in IO when using GHC. 但在实践中,您可以使用其他答案中的方法在使用GHC时在IO中捕获它。 Exceptions cannot be caught in pure (non-IO) code because raising an exception is a change in control flow is a side effect, not a pure computation. 异常不能在纯(非IO)代码中捕获,因为引发异常是控制流的变化是副作用,而不是纯计算。

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

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