F#如何捕获所有异常 [英] F# How to catch all exceptions

查看:52
本文介绍了F#如何捕获所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know how to catch specific exceptions as in the following example:

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 中使用通用异常,例如通配符匹配.是否存在这样的构造?如果存在,那么它是什么?

I am reading a bunch of articles to see if I can use a generic exception in the with, like a wildcard match. Does such a construct exist, and, if so, what is it?

推荐答案

我喜欢您应用类型模式测试的方式(请参阅

I like the way that you applied the type pattern test (see link). The pattern you are looking for is called the wildcard pattern. Probably you know that already, but didn't realise that you could use it here, too. The important thing to remember is that the with part of a try-catch block follows match semantics. So, all of the other nice pattern stuff applies here, too:

使用您的代码(以及一些修饰,以便您可以在FSI中运行它),这是执行操作的方法:

Using your code (and a few embellishments so that you can run it in FSI), here's how to do it:

#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

这篇关于F#如何捕获所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆