我在捕捉异常方面遇到了一些麻烦:
private static void WriteLog(string line, string currentDirectory, string dataLocation, int retries)
{
string localPath = currentDirectory + dataLocation;
// Write CSV header if the log file does not yet exist
bool writeHeader = !File.Exists(localPath);
try
{
using (StreamWriter sw = File.AppendText(localPath))
{
LogMessage("Log file opened. Writing...");
if (writeHeader)
sw.WriteLine(csvHeader);
sw.WriteLine(line);
sw.Close();
LogMessage("Wrote line successfully. Log file closing.");
}
}
catch (IOException e)
{
if (++retries > 3) return;
LogMessage($"Cannot write to file because it is open. Retrying.. {retries}/3 (Exception: {e.Message})");
var retryDuration = TimeSpan.FromTicks(ApplicationSettings.AnalysisInterval.Ticks / 3);
Thread.Sleep(retryDuration);
WriteLog(line, currentDirectory, dataLocation, retries);
}
LogMessage($"Logged line after {retries} retries.");
Task.Run(() => DropboxUploader.UploadCsv(localPath, dataLocation));
}
StreamWriter sw = File.AppendText(localPath)是抛出IOException的行。正如您所看到的,我尝试使用try / catch块捕获它,但IOException仍然被抛出。这似乎也发生在其他例外情况下。有人知道为什么异常仍然被抛出?
答案 0 :(得分:0)
try-clause中抛出的所有IOExceptions都将在catch子句中捕获。 要么它不是被抛出的IOException,也许它只是一个例外?
或者,如果它是抛出的IOException,则它源自try子句之后发生的事情。
EG。我注意到你在catch子句和try-catch子句之后尝试记录东西。我猜你把数据写入文件,如果出现问题,最有可能抛出IOException