Catching IOException

17,498

Solution 1

As you can see here File.OpenRead can throw these exception type

  1. ArgumentException
  2. ArgumentNullException
  3. PathTooLongException
  4. DirectoryNotFoundException
  5. UnauthorizedAccessException
  6. FileNotFoundException
  7. NotSupportedException

for each of this exception type you can handle it in this way

try{

}
catch(ArgumentException e){
  MessageBox.Show("ArgumentException ");
}
catch(ArgumentNullExceptione e){
 MessageBox.Show("ArgumentNullExceptione");
}
.
.
.
.        
catch(Exceptione e){
     MessageBox.Show("Generic");
}

In your case you can handle just one or two types and other are always catched by generic Exception (it must be always the lastone because cathces all Exceptions)

Solution 2

Always catch from the most specific to the most generic exception type. Every exception inherits the Exception-class, thus you will catch any exception in your catch (Exception) statement.

This will filter IOExceptions and every else separately:

catch (IOException ioEx)
{
     HandleIOException(ioEx);
}
catch (Exception ex)
{
     HandleGenericException(ex);
}

So catch Exception always last. Checking with if is possible, but not common.

About your problem:

if (File.Exists(filePath)) // File still exists, so obviously blocked by another process

This would be the simplest solution to separate your conditions.

Share:
17,498
user3202144
Author by

user3202144

Updated on June 04, 2022

Comments

  • user3202144
    user3202144 almost 2 years

    I am writing a C# application in which I have to display a message if File is already being used by some process and if the file doesnot exist, the application needs to display another message.

    Something like this:

    try 
    {
        //Code to open a file
    }
    catch (Exception e)
    {
        if (e IS IOException)
        {
            //if File is being used by another process
            MessageBox.Show("Another user is already using this file.");
    
            //if File doesnot exist
            MessageBox.Show("Documents older than 90 days are not allowed.");
        }
    }
    

    Since IOException covers both the conditions, how do I distinguish if this exception is caught because of File being used by another process or File doesnot exist?

    Any help would be highly appreciated.