我正在解析一个不时包含MalFormed数据的文件。
它抛出了一个异常,
我希望从异常中恢复,并忽略格式错误的数据。
做这件事最好的方法是什么?
try{
// parse file
}catch(Exception){
//eat it.
}编辑:*我想,我的问题没有被很好的理解。我想从异常中恢复过来,任何例外情况下,我不希望我的程序停止。而是继续。
发布于 2010-10-19 22:17:34
我想你要问的是:
在逐行解析文件时,有时当前行有格式错误的数据,这会导致在代码中抛出异常。也许您只需要构造代码,使try/catch只包围解析代码,而不是行读取代码。例如:
using System;
using System.IO;
using System.Windows.Forms;
public void ParseFile(string filepath)
{
TextReader reader = null;
try
{
reader = new StreamReader(filepath);
string line = reader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
try
{
// parse line here; if line is malformed,
// general exception will be caught and ignored
// and we move on to the next line
}
catch (Exception)
{
// recommended to at least log the malformed
// line at this point
}
line = reader.ReadLine();
}
}
catch (Exception ex)
{
throw new Exception("Exception when trying to open or parse file", ex);
}
finally
{
if (reader != null)
{
reader.Close();
reader.Dispose();
}
reader = null;
}
}外部try/catch块是在试图打开或读取文件时发生了什么事情时,正确地处理关闭读取器对象。内部try/catch块是在读取的数据格式错误且不能正确解析时吞下引发的异常。
不过,我同意其他人的意见。只是吞咽例外可能不太好。至少,我建议你把它写在某个地方。
发布于 2010-10-19 21:27:24
简而言之,您可能不应该为此使用异常。类似于返回false的TryParse更高效,更容易从其中恢复。异常处理是一种有点钝的对象方法。
MSDN异常处理指南
发布于 2010-10-19 21:30:39
一般来说,类似这样的情况:
try
{
// parse file
}
catch (FormatException)
{
// handle the exception
}
finally
{
// this block is always executed
}您应该避免捕获一般的Exception情况,而应该捕获特定的异常,不管这是什么。
https://stackoverflow.com/questions/3972887
复制相似问题