Obviously a lot of applications will need to work with files and display errors to users. However memebers of System.IO.File class throw a lot of exceptions. These are just for ReadAllText:
- ArgumentException
- ArgumentNullException
- PathTooLongException
- DirectoryNotFoundException
- IOException
- UnauthorizedAccessException
- FileNotFoundException
- NotSupportedException
- SecurityException
So how to catch them all and display them to user while not swallowing other exceptions?
Obviously with perfect coding you can eliminate these 2:
- ArgumentException
- ArgumentNullException
If you write a (possibly painful) check you can eliminate PathTooLongException. But why would you duplicate code for check that Microsoft has written?
But other exceptions can still happen even if you did all the checks:
- DirectoryNotFoundException
- IOException
- UnauthorizedAccessException
- FileNotFoundException
- NotSupportedException
- SecurityException
Files and folders can get deleted by the time you open the file, security permissions can change etc.
I don't see what you can do in these scenarios except display message to user. Are you going to find directory that OS can't find? Fix the permissions? Inject code into OS to make unsupported operation supported? LOL All I see possible is to display an error message.
So if I have to catch all of these exceptions every time I open a file to read text my code would have to be long and repetitive, unless I swallow exceptions by catching Exception.
Would it be good practice to create a FileException and just catch all exceptions that can come up when actually working with files? What I had in mind is this:
public class FileException : Exception
{
public FileException( Exception e )
: base( e.Message, e.InnerException )
{
}
}
public static class FileNoBS
{
public static string ReadAllText2( string path )
{
try
{
return File.ReadAllText( path );
}
catch ( ArgumentNullException e )
{
throw new FileException( e );
}
catch ( ArgumentException e )
{
throw new FileException( e );
}
catch ( PathTooLongException e )
{
throw new FileException( e );
}
catch ( DirectoryNotFoundException e )
{
throw new FileException( e );
}
catch ( FileNotFoundException e )
{
throw new FileException( e );
}
catch ( IOException e )
{
throw new FileException( e );
}
catch ( UnauthorizedAccessException e )
{
throw new FileException( e );
}
catch ( NotSupportedException e )
{
throw new FileException( e );
}
catch ( SecurityException e )
{
throw new FileException( e );
}
}
}
Then when catching exceptions I would just have to write this:
try
{
string text = FileNoBS.ReadAllText2( path );
}
catch ( FileException e )
{
// display error to user
}
I don't really understand why Microsoft has not grouped all those exceptions togather in some way. Am I missing something or is this good practice?