问题描述
我知道如何捕获特定的异常,如以下示例所示:
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?
推荐答案
我喜欢您应用类型模式测试的方式(请参阅链接).您要查找的模式称为通配符模式.也许您已经知道这一点,但是没有意识到您也可以在这里使用它.要记住的重要一点是,try-catch块的 with 部分遵循匹配语义.因此,所有其他好的模式也适用于此:
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#如何捕获所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!