1

this code is used as an example, and to show the exception.

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")

The "http://fsharp.org/working" throws a 'System.Net.WebException' because it doesn't exist and the for loop stops. I want that the loop continues with the next string, in this case "teaching".

I have tried to handle the exception with try...with and also adding reraise() but I haven't solved the problem yet.

2 Answers2

5

A try..with like this will swallow all exceptions:

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

You can change this to handle specific errors, or perform some logging, etc.

Another throught... If you're using Visual Studio and have it configured to "Break on Exception", you might just be seeing the Debugger handling the exception in your try..with, you can just "F5" past it, disable the debugging breaking, or run it out of the debugger.

Community
  • 1
  • 1
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
  • I have tried this = and I can't F5 past it - it always breaks the whole process even though I have that setting turned off as well..? – Martin Thompson Feb 21 '21 at 07:44
1

NOTE: I'm still learning F#. However, I would like to try to share what I have learned.

Extending DaveShaw's answer, you can also let your client decide how to handle the exception versus the server making the decision without the client's permission.

The code below conveys how a client can provide a handler (i.e. OnFailure) when an exception is exposed:

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

Output:

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.
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118