简体   繁体   English

为什么F#failwith返回泛型类型而不是Exception类型

[英]why does F# failwith return a generic type rather than Exception type

According to the docs the failwith function returns an Exception But the function signature is string -> 'a 根据文档 ,failwith函数返回一个Exception但函数签名是string -> 'a

Why is the signature not string -> Exception ? 为什么签名不是string -> Exception

The docs don't say that failwith returns an Exception . 文档并没有说failwith返回Exception It says it generates an F# exception. 它说它会产生一个F#异常。 The exception system is separate from the normal control flow of returning values. 异常系统与返回值的正常控制流分开。 Hence the name, it's exceptional . 因此这个名字,它是特殊的

Exceptions, when "thrown" (which is a less ambiguous term than "generated" as used in the docs, I think), will travel up the stack until encountering a try ... with construct that handles this particular type of exception, or if not will terminate the program. 例外情况,当“抛出”(这是一个比文档中使用的“生成”更不模糊的术语,我认为),将在堆栈中向上移动,直到遇到try ... with处理此特定类型的异常的构造,或者如果没有将终止该程序。 See the F# docs on exception handling for details. 有关详细信息,请参阅有关异常处理的F#文档

failwith returns 'a so that it can be used anywhere, since 'a can be inferred to be anything. failwith返回'a以便它可以在任何地方使用,因为'a可以被推断为任何东西。 It can pretend to return anything because it never actually returns at all, unlike most functions, it always throws an exception instead. 它可以假装返回任何内容,因为它根本不会实际返回,与大多数函数不同,它总是抛出异常。 If it had returned Exception it would only be able to be used in expressions that are expected to evaluate to Exception , which are exceptionally unusual since exceptions are usually thrown, not returned. 如果它已经返回Exception那么它只能用于期望评估为Exception表达式中,这种情况异常罕见,因为通常会抛出异常,而不会返回异常。 For example, given: 例如,给定:

if i > 0 then
  i
else
  failwith "i is negative"

If failwith had returned Exception , the compiler would complain here about an int being expected instead of an Exception since the first branch evaluates to an int . 如果failwith返回了Exception ,那么编译器会在这里抱怨一个int被期望而不是Exception因为第一个分支的计算结果为int But since failwith returns an 'a instead, it's inferred to be an int itself and everything is fine. 但是因为failwith返回一个'a而不是,它被推断为一个int本身,一切都很好。

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

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