无法捕获htmldocument加载异常

时间:2013-08-27 19:48:11

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

有时候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) + "/");

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

提供另一种解决方案。你的捕获是针对ArgumentException并且仅捕获 ArgumentException ...带来的是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
}

答案 1 :(得分:1)

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

将您的代码更改为:

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

答案 2 :(得分:1)

您的代码仅捕获ArgumentException

如果你想捕捉其他类型的例外,你需要改变它。