使用Failwith关键字的F#抛出异常

在F#中, 可以显式抛出异常。你可以引发自定义异常。你还可以使用Exception的预定义方法(例如Failwith和InvalidArgs)引发异常。 Failwith关键字生成System.Exception异常。它具有Failure关键字来引用异常。让我们来看一个例子。

let TestAgeValidation age=tryif (age< 18) then failwith "Sorry, Age must be greater than 18"with| Failure(e) -> printfn "%s" e; printf "Rest of the code"TestAgeValidation 10

输出:
Sorry, Age must be greater than 18Rest of the code

使用InvalidArg关键字的F#抛出异常它生成System.ArgumentException。你可以使用InvalidArg引发参数类型异常。让我们来看一个例子。
let TestInvalidArgument age = if(age< 18) theninvalidArg "TestInvalidArgument" ("Sorry, Age must be greater than 18")TestInvalidArgument 10

【使用Failwith关键字的F#抛出异常】输出:
System.ArgumentException: Sorry, Age must be greater than 18

    推荐阅读