[英]Is it good practice to put try-catch in a loop until all statements in the try block is executed without any exceptions?
[英]Is it bad Practice to Put a Try-Catch in a For Loop?
我正在創建一個命令行實用程序,它將刪除子目錄/文件。 如果文件正在使用中,則拋出System.IO.IOException
。 我在 for 循環中使用了 try-catch 塊。
題:
1. 在 for 循環中進行 try-catch 是不好的做法嗎?
2.如果是,什么是更好的選擇?
我的代碼:
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(System.IO.IOException)
{
Console.WriteLine("Please Close the following File {0}", file.Name);
}
}
不,這可能非常有用。 例如:如果您不想在拋出異常時完全停止循環,或者如果由於異常而存在不應為當前迭代運行的額外代碼,您可以執行以下操作。
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(System.IO.IOException)
{
Console.WriteLine("Please Close the following File {0}", file.Name);
continue;
}
//
// Other Code
//
}
通過這種方式,您可以記錄錯誤以供稍后查看,但仍會處理您嘗試處理的其余部分。
不,故意跳過異常並不是一個壞習慣。 但是看看你的用例
我正在創建一個命令行實用程序,它將刪除子目錄/文件。 如果文件正在使用,則拋出 System.IO.IOException。
我建議您刪除目錄,而不是在子文件夾中的每個文件上循環。 https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.delete?view=net-5.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.