吃异常

Dar*_*der 7 .net c# error-handling exception

我正在解析一个不时有MalFormed数据的文件.

这是一个例外,

id喜欢从异常中恢复并忽略格式错误的数据.

最好的方法是什么?

try{
// parse file
}catch(Exception){
//eat it.
}
Run Code Online (Sandbox Code Playgroud)

*编辑:*我想,我的问题不是很清楚.我喜欢从异常中恢复,任何异常,我不希望我的程序停止.但要继续

Tho*_*rin 8

我想你问的是这个:

逐行解析文件时,有时当前行的数据格式错误,导致代码中抛出异常.也许您只需要构造代码,使得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;
    }
}
Run Code Online (Sandbox Code Playgroud)

外部try/catch块用于在尝试打开或读取文件时发生某些事情时正确关闭读取器对象.如果读取数据格式错误且无法正确解析,则内部try/catch块将吞下引发的异常.

不过,我同意其他所有人的意见.吞下异常可能不太好.至少,我建议你把它记录在某个地方.

  • 在外部catch中,你需要使用`throw;`而不是将原始的Exception包装在一个新的,以保留调用堆栈.此外,如果你使用`using(reader = new StreamReader(filepath))`那么你无论如何都不需要那个外部异常块. (2认同)

hem*_*emp 5

简而言之,您可能不应该使用异常.像TryParse这样返回false的东西效率更高,更容易恢复.异常处理是一种钝的对象方法.

MSDN异常处理指南

  • 只有在阅读提供TryParse方法的一些基本类型时,TryParse才有意义.如果从文件流中解析并且该文件丢失,则无法使用"TryParse"而无异常 - 您将需要异常处理*某处*来处理FileNotFoundException. (2认同)