在 System.IO 中有一个函数:string File.ReadAllText(string path);
我正在尝试编写一个调用 File.ReadAllText 的函数,处理所有可能的异常并返回 true/false 并存储错误消息。
我所拥有的是:
public static class FileNoBS
{
public static bool ReadAllText( string path, out string text, out string errorMessage )
{
errorMessage = null;
text = null;
bool operationSuccessful = false;
try
{
text = System.IO.File.ReadAllText( path );
operationSuccessful = true;
}
catch ( ArgumentNullException e )
{
errorMessage = "Internal software error - argument null exception in FileNoBs.ReadAllText\nMessage: " + e.Message;
}
catch ( ArgumentException e )
{
errorMessage = "Internal software error - path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars in FileNoBs.ReadAllText.\nMessage: " + e.Message;
}
catch ( PathTooLongException e )
{
errorMessage = "The specified path was too long.\nMessage: " + e.Message;
}
catch ( DirectoryNotFoundException e )
{
errorMessage = "The specified directory was not found.\nMessage: " + e.Message;
}
catch ( FileNotFoundException e )
{
errorMessage = "The file specified in path was not found.\nMessage: " + e.Message;
}
catch ( IOException e )
{
errorMessage = "An I/O error occurred while opening the file.\nMessage: " + e.Message;
}
catch ( UnauthorizedAccessException e )
{
errorMessage = @"UnauthorizedAccessException
path specified a file that is read-only.
-or-
This operation is not supported on the current platform.
-or-
path specified a directory.
-or-
The caller does not have the required permission.\nMessage: " + e.Message;
}
catch ( NotSupportedException e )
{
errorMessage = "path is in an invalid format.\nMessage: " + e.Message;
}
catch ( SecurityException e )
{
errorMessage = "You do not have the required permission.\nMessage: " + e.Message;
}
return operationSuccessful;
}
}
我不明白控制流如何与返回值的函数一起使用。假设 UnauthorizedAccessException 被捕获,errorMessage 设置为
errorMessage = "You do not have the required permission..."
我知道 finally 每次都会执行,但是编译器不会让我在 finally 块中返回。那么我的回报是否会达到?
另一个问题是如何在遵循官方指南的同时简化这一过程:“一般来说,你应该只捕获那些你知道如何从中恢复的异常。”
我害怕从 File 类(Move、Copy、Delete、ReadAllText、WriteAllText)和 Directory 类中遍历我需要的所有函数,并执行所有这些长代码块只是为了捕获所有我不关心和不捕获的异常太多了,因为微软说它很糟糕。
谢谢你。
编辑:我得到这样的评论不是处理异常这是“别的东西”。
我是我的代码的客户,我想做这样的事情:
if ( !FileNoBS.ReadAllText( path, text, errorMessage ) ) {
MessageBox.Show( errorMessage );
return;
}
// continue working with all errors taken care of - don't care for whatever reason file wasn't opened and read, user is notified and I am moving on with my life