gpt4 book ai didi

c# - 执行文件io时如何正确处理异常

转载 作者:可可西里 更新时间:2023-11-01 03:08:49 25 4
gpt4 key购买 nike

我经常发现自己以某种方式与文件交互,但在编写代码后,我总是不确定它实际上有多健壮。问题是我不完全确定文件相关操作会如何失败,因此也不确定处理异常的最佳方式。

简单的解决方案似乎只是捕获代码抛出的任何 IOExceptions 并向用户提供“无法访问的文件”错误消息,但是否有可能获得更细粒度的错误信息?有没有办法确定文件被另一个程序锁定等错误与由于硬件错误导致数据不可读之间的区别?

给定以下 C# 代码,您将如何以用户友好(尽可能提供信息)的方式处理错误?

public class IO
{
public List<string> ReadFile(string path)
{
FileInfo file = new FileInfo(path);

if (!file.Exists)
{
throw new FileNotFoundException();
}

StreamReader reader = file.OpenText();
List<string> text = new List<string>();

while (!reader.EndOfStream)
{
text.Add(reader.ReadLine());
}

reader.Close();
reader.Dispose();
return text;
}

public void WriteFile(List<string> text, string path)
{
FileInfo file = new FileInfo(path);

if (!file.Exists)
{
throw new FileNotFoundException();
}

StreamWriter writer = file.CreateText();

foreach(string line in text)
{
writer.WriteLine(line);
}

writer.Flush();
writer.Close();
writer.Dispose();
}
}

最佳答案

...but is it possible to get a bit more fine-grained error messages.

是的。继续捕获IOException,并使用Exception.ToString() 方法获取相对相关的错误消息来显示。请注意,.NET Framework 生成的异常将提供这些有用的字符串,但如果您要抛出自己的异常,则必须记住将该字符串插入 Exception 的构造函数中,例如:

throw new FileNotFoundException("找不到文件");

此外,绝对按照 Scott Dorman ,使用那个 using 语句。不过,需要注意的是,using 语句实际上并没有catch 任何东西,这本该是这样的。例如,您查看文件是否存在的测试将引入一个可能相当 vexing 的竞争条件。 .把它放在那里真的对你没有任何好处。所以,现在,对于读者,我们有:

try {  
using (StreamReader reader = file.OpenText()) {
// Your processing code here
}
} catch (IOException e) {
UI.AlertUserSomehow(e.ToString());
}

简而言之,对于基本的文件操作:
1.使用using
2,将using语句或函数包装在try/catch中,catches IOException
3. 在您的catch 中使用Exception.ToString() 来获取有用的错误消息
4. 不要尝试自己检测异常文件问题。让 .NET 为您进行 throw 。

关于c# - 执行文件io时如何正确处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/86766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com