F#中的异常后继续循环

时间:2017-03-27 17:18:50

标签: .net f#

此代码用作示例,并显示异常。

open System.Net

let baseUrl = "http://fsharp.org/"
let someWords = ["learn"; "working"; "teaching"; "testimonials"] 

let downloadFile (url : string) (filePath : string) =
    use wc = new System.Net.WebClient()
    wc.DownloadFile(url, filePath)

for words in someWords do
    let joinedUrl =
        baseUrl
        + words.ToString()
    System.Console.WriteLine(joinedUrl)
    downloadFile joinedUrl (@"C:\temp\file" + words + ".txt")

http://fsharp.org/working”会抛出' System.Net.WebException ',因为它不存在且for loop停止。 我希望循环继续下一个字符串,在本例中为“teaching”。

我尝试使用try...with处理异常并添加reraise(),但我还没有解决问题。

2 个答案:

答案 0 :(得分:5)

尝试这样做会吞下所有例外情况:

let downloadFile (url : string) (filePath : string) =
    try
        use wc = new System.Net.WebClient()
        wc.DownloadFile(url, filePath)
    with _ -> //Matches all exception types
        ()    //returns unit

您可以更改此项以处理特定错误,或执行某些日志记录等。

另一个经历...如果您正在使用Visual Studio并将其配置为“Break on Exception”,您可能只是看到调试器在try..with中处理异常,您可以只是“F5” “过去它,禁用调试中断,或者从调试器中运行它。

答案 1 :(得分:1)

注意:我还在学习F#。但是,我想尝试分享我所学到的知识。

扩展DaveShaw的答案,你也可以让你的客户决定如何处理异常,而不是服务器在未经客户许可的情况下作出决定。

下面的代码说明了客户端在暴露异常时如何提供处理程序(即OnFailure):

open System.Net
open System

let baseUrl = "http://fsharp.org/"
let someWords = ["learn"; "working"; "teaching"; "testimonials"] 

let downloadFile (url : string) (filePath : string) (onFailure : string -> unit) =
    try use wc = new System.Net.WebClient()
        wc.DownloadFile(url, filePath)

    with ex -> onFailure ex.Message

for words in someWords do
    let joinedUrl =
        baseUrl
        + words.ToString()
    System.Console.WriteLine(joinedUrl)

    let onFailure = printfn "%s"
    downloadFile joinedUrl (@"C:\temp\file" + words + ".txt") onFailure

<强>输出:

http://fsharp.org/learn
An exception occurred during a WebClient request.
http://fsharp.org/working
An exception occurred during a WebClient request.
http://fsharp.org/teaching
An exception occurred during a WebClient request.
http://fsharp.org/testimonials
An exception occurred during a WebClient request.