F#如何捕获所有异常

7

我知道如何捕获特定的异常,就像以下示例:

let test_zip_archive candidate_zip_archive =
  let rc =
      try
        ZipFile.Open(candidate_zip_archive.ToString(), ZipArchiveMode.Read) |> ignore
      zip_file_ok
      with
      | :? System.IO.InvalidDataException -> not_a_zip_file
      | :? System.IO.FileNotFoundException -> file_not_found         
      | :? System.NotSupportedException -> unsupported_exception
  rc

我正在阅读一堆文章,看是否可以在 with 中使用通用异常,就像通配符匹配一样。 是否存在这样的构造,如果存在,它是什么?

2个回答

16

是的,你可以这样做:

let foo = 
  try
    //stuff (e.g.)
    //failwith "wat?"
    //raise (System.InvalidCastException())
    0 //return 0 when OK
  with ex ->
    printfn "%A" ex //ex is any exception 
    -1 //return -1 on error

这与C#的 catch (Exception ex) { } 相同。

要丢弃错误,您可以使用 with _ -> -1(与C#的 catch { } 相同)


这非常有帮助。谢谢。 - octopusgrabbus

8
我喜欢你应用了类型模式测试(请参见链接)。你要寻找的模式被称为通配符模式。也许你已经知道了,但没有意识到在这里也可以使用它。
重要的是要记住try-catch块的with部分遵循匹配语义。因此,所有其他好的模式都适用于这里: 使用你的代码(并加入一些修饰以便在FSI中运行),以下是如何做到这一点:
#r "System.IO.Compression.FileSystem.dll"
#r "System.IO.Compression.dll"

open System  
open System.IO
open System.IO.Compression

type Status = 
  | Zip_file_ok
  | Not_a_zip_file
  | File_not_found
  | Unsupported_exception
  | I_am_a_catch_all

let test_zip_archive candidate_zip_archive =
  let rc() =
    try
      ZipFile.Open(candidate_zip_archive.ToString(), ZipArchiveMode.Read) |> ignore
      Zip_file_ok
    with
    | :? System.IO.InvalidDataException -> Not_a_zip_file
    | :? System.IO.FileNotFoundException -> File_not_found         
    | :? System.NotSupportedException -> Unsupported_exception
    | _ -> I_am_a_catch_all // otherwise known as "wildcard"
  rc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接