wingerse
wingerse

Reputation: 3796

Handling an WebException in C#

I have this code:

public static string HttpGet(string URI)
    {
        System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
        System.Net.WebResponse resp = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        return sr.ReadToEnd().Trim();
    }
        try
        {
            SetInterval(() =>
            {
                string r = HttpGet("http://www.example.com/some.php?Username= Z&Status=On");
            }, 10000);
        }
        catch (WebException) { MessageBox.Show("No Network!"); }

What the Setinterval() does in retry run the code every 10000 milliseconds. But If I am not connected to internet, it gives me a WebException error. But it seems I can't even handle it. catching the exception still gives me the same error. Is there any way to just say 'Do nothing' when the error occurs?

P.S I am new to C#.

EDIT: Here's the code for setinterval:

public static IDisposable SetInterval(Action method, int delayInMilliseconds)
    {
        System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
        timer.Elapsed += (source, e) =>
        {
            method();
        };

        timer.Enabled = true;
        timer.Start();

        // Returns a stop handle which can be used for stopping
        // the timer, if required
        return timer as IDisposable;
    }

Upvotes: 0

Views: 2476

Answers (1)

David
David

Reputation: 218818

You're catching the exception when you invoke SetInterval (which itself probably never throws a WebException), but not in the anonymous function which is being executed in the context of that interval. Move your exception handling into that function:

SetInterval(() =>
{
    try
    {
        string r = HttpGet("http://www.example.com/some.php?Username= Z&Status=On");
    }
    catch (WebException) { MessageBox.Show("No Network!"); }
}, 10000);

Upvotes: 2

Related Questions