在Try/Catch之后,回到Foreach循环
本文关键字:回到 Foreach 循环 之后 Try Catch | 更新日期: 2023-09-27 18:16:43
我构建了一些CodeExample:
static void Main(string[] args)
{
foreach (String hello in helloList)
{
DoSomething(hello);
}
}
public static void DoSomething(String hello)
{
try
{
//Some Code
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadKey();
}
}
我正在遍历List,有时程序会进入Catch。现在,程序终止了,在Console.ReadKey();
之后-但我想要的是,回到foreach循环并继续工作…我怎样才能做到这一点呢?从Catch中,我只需要Message.
编辑:OriginalCode:
static void Main(string[] args)
{
//Some unimportant code
StringCollection bilderUnterLink = HoleBildLinksVonWebseite(htmlInhaltUnterLink);
foreach (String bild in bilderUnterLink)
{
BildAbspeichern(bild);
}
}
public static void BildAbspeichern(String bildLink)
{
string speicherOrt = webseite + @"/" + bildLink;
string gueltigerBildLink;
if (bildLink.Contains("http://"))
{
gueltigerBildLink = bildLink;
}
else
{
gueltigerBildLink = "http://" + webseite + @"/" + bildLink;
}
if (!File.Exists(webseite + @"/" + Path.GetFileName(gueltigerBildLink)))
{
try
{
WebClient client = new WebClient();
client.DownloadFile(gueltigerBildLink, speicherOrt);
Console.WriteLine(String.Format("Bild gepeichert: " + "{0}", gueltigerBildLink));
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadKey();
}
}
}
我认为这足够重要的代码…它终止了,我知道它不应该。
如果它正在终止,我怀疑异常只是不在try
内;所以…变化:
public static void BildAbspeichern(String bildLink)
{
try {
... all your code
} catch (Exception exception)
{
Console.Error.WriteLine(exception.Message);
Console.ReadKey();
}
}
其他笔记:
- 注:我更改为
Console.Error
错误输出;良好实践(写入stderr
而不是stdout
) - 等待按键而不告诉用户你在等待可能会造成混淆;就我个人而言,我会完全删除
ReadKey()
你应该在
WebClient
上使用using
,因为它是IDisposable
,即using(var client = new WebClient()) { client.DownloadFile(gueltigerBildLink, speicherOrt); }
这将在异常之后继续循环。
由于您在DoSomething()
方法中捕获异常,因此不会中断循环。只有DoSomething()
内部未处理的异常才会中断循环。