我有一个解析文件的方法。但是,这种解析可能会随时失败,具体取决于各种情况(例如,不那么谨慎的用户使用该文件)。
public string ParseDatFile(string datFile)
{
string[] deezLines = File.ReadAllLines(datFile);
// We're searching for an essential data inside the file.
bool daEssentialDataFound = false;
foreach (string datLine in deezLines)
{
if (datLine.Contains("daEssentialData"))
{
daEssentialDataFound = true;
break;
}
}
if (!daEssentialDataFound)
throw new WhatShouldIThrowException("yo dood where's da essential data in " + datFile + "?");
DoStuffWith(deezLines);
}
在这种情况下我可以使用异常(exception)吗?我考虑过:
- FormatException:问题不是很清楚,
- 自定义异常:我对抛出的异常没有任何特殊处理,所以我宁愿避免使用自定义异常,尽管这始终是解决问题的一种方式。
最佳答案
FileFormatException应该没问题:
The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed.
您可以选择提供 uri 和描述性错误消息。
如果您不想引用 WindowsBase
,那么您可以针对您的格式创建自己的异常。基于 XmlReader.Read
抛出的 XmlException
这一事实.
关于c# - 我应该为失败的文件解析抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281600/