【问题标题】:cannot catch htmldocument load exception无法捕获 htmldocument 加载异常
【发布时间】:2013-08-30 17:12:31
【问题描述】:

有时 htmlDocument.Load(url) 会给我这个异常:

Unhandled Exception: System.IO.IOException: Unable to read data from the transpo
rt connection: An existing connection was forcibly closed by the remote host. --

很遗憾,我无法捕捉到这个异常。

我发现异常如下:

try
{
   page = web.Load(url + Convert.ToString(i + 1) + "/");
}
catch (ArgumentException ex)
{
  //do something
}

当我运行程序时,异常仍然在写入的那一行停止程序:

page = web.Load(url + Convert.ToString(i + 1) + "/");

有人可以帮我吗?

【问题讨论】:

    标签: c# exception error-handling try-catch dom


    【解决方案1】:

    只是提供另一种解决方案。您的捕获是针对ArgumentException 并且将捕获 ArgumentExceptions...所带来的是IOException

    如果您只是想捕获 try 块抛出的所有异常,您可以将代码更改为以下内容:

    try
    {
       page = web.Load(url + Convert.ToString(i + 1) + "/");
    }
    catch (Exception ex)
    {
        //do something
    }
    

    如果你想为每个异常做不同的事情:

    try
    {
       page = web.Load(url + Convert.ToString(i + 1) + "/");
    }
    catch (ArgumentException ex)
    {
        //do something about ArgumentException
    }
    catch (System.IO.IOException ex) 
    {
        //do something about IOException
    }
    

    【讨论】:

      【解决方案2】:

      这是因为抛出的异常是 System.IO.IOException,而您正在捕获 ArgumentException

      将您的代码更改为:

      try
      {
         page = web.Load(url + Convert.ToString(i + 1) + "/");
      }
      catch (System.IO.IOException ex)
      {
        //do something
      }
      

      【讨论】:

        【解决方案3】:

        您的代码仅捕获ArgumentExceptions。

        如果你想捕获其他类型的异常,你需要改变它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-29
          • 1970-01-01
          • 2021-10-09
          • 2021-09-17
          • 2021-10-03
          • 2018-02-04
          相关资源
          最近更新 更多