【问题标题】:Handling an WebException in C#在 C# 中处理 WebException
【发布时间】:2014-09-10 17:40:48
【问题描述】:

我有这个代码:

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!"); }

Setinterval() 在重试中的作用是每 10000 毫秒运行一次代码。 但是如果我没有连接到互联网,它会给我一个 WebException 错误。但似乎我什至无法处理它。捕获异常仍然给我同样的错误。发生错误时有什么方法可以说“什么都不做”?

P.S 我是 C# 新手。

编辑: 这是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;
    }

【问题讨论】:

  • 您看到了什么错误?没有网络是您对 WebException 的期望。如果您抛出了另一种异常,那么它仍然会抛出,因为您只是在捕获 WebException。如果您通过 Visual Studio 运行它,那么您仍然会看到一个异常,但是您应该会收到您的消息,再次假设它是 WebException。
  • 这是我仍然得到的错误:An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code Additional information: The remote name could not be resolved: 'example.com' If there is a handler for this exception, the program may be safely continued.

标签: c# exception system.net


【解决方案1】:

当您调用SetInterval(它本身可能永远不会抛出WebException)时,您正在捕获异常,但不是在该区间上下文中执行的匿名函数中。将您的异常处理移到该函数中:

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

【讨论】:

  • 为什么在这种情况下异常没有冒泡?
  • @Hammerstein:我不熟悉这里的SetInterval 的实现,但大概它会卸载到一个单独的线程(或至少类似的线程)并将控制权返回给调用代码。这意味着 try 块在匿名函数执行之前完成而没有错误。它们不再在同一个堆栈上,因此异常不会向上移动该堆栈。 (OP 可以检查异常的堆栈跟踪以确认这一点。)
  • 明白了,这是有道理的。感谢您的澄清。
  • 感谢 David,将 try 块放在 setinterval 中就可以了!
猜你喜欢
  • 2011-02-08
  • 2015-12-15
  • 2010-12-30
  • 2013-10-24
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多