迅速捕获异常

Catch exception in sharp

我制作了一个程序,用户可以在终端中输入 commandos,但是当用户输入“quit”时出现异常。我怎么抓住它?下面的代码只是一个片段,因为我的代码真的很长。

  let mutable input = ""
  while myTurn = true do 
  input <- System.Console.ReadLine()
  match input with
  |_ when input = "quit" -> (myTurn <- false)
  |_ -> printfn "Incorrect input"

现在,当我输入“退出”时,我的终端会显示 System.IndexOutOfRangeException 但是,如果我将“退出”更改为任何其他词,它就会起作用。有什么方法可以让它与 quit 这个词一起使用吗?

您发布的代码无法编译(myTurn、startPos、endPos 未定义),所以不,它不是 Sergey Berezovskiy 要求的真正的 MRE。即使你的代码修改为

let mutable myTurn = true
let mutable input = ""
while myTurn = true do 
    input <- System.Console.ReadLine()
    match input with
    |_ when input = "quit" -> (myTurn <- false)
    |_ -> printfn "Incorrect input"

输入“退出”时不会抛出异常。所以我没办法帮你查到异常。

但是,您实际上问的是如何捕获异常,为此您需要 try ... with ...。例如

try potentiallyThrowingFunction "abc" 123
with e -> printfn "Oh snap!"

将捕获任何异常并将某些内容打印到控制台。异常处理路径需要 return 与 try-path 相同的类型,所以如果 potentiallyThrowingFunction return 是 int,异常处理代码需要 return 一个 int (或抛出一个新的异常或重新抛出原始异常)。

实际上,如果您想以不同的方式处理不同的异常,您可以使用 try ... with ... 对异常进行模式匹配;例如

try potentiallyThrowingFunction "abc" 123
with 
    | :? System.ArgumentException as e -> 
        printfn "Oh dang! ArgumentException: %s" e.Message
    | :? System.IndexOutOfRangeException as e ->
        printfn "Woops, IndexOutOfRangeException: %s" e.Message