在F#中, 你可以创建用户定义的异常。它提供了根据需求定义自定义异常的灵活性。让我们来看一个例子。
exception InvalidAgeException of string
let validate x =
if (x < 18) then
raise (InvalidAgeException "Sorry, Age must be greater than 18")
let TestUserDefinedException =
try
validate 15
with
| InvalidAgeException(e) -> printfn "%s" e
printfn "Rest of the code"
TestUserDefinedException
输出:
Sorry, Age must be greater than 18
Rest of the code
评论前必须登录!
注册