Pedro77
Pedro77

Reputation: 5294

Why ArgumentException from Directory.Exist can not be catched?

Why I can't catch the Argument excpetion here:

        string path = "\"";
        bool dirOk = true;
        try
        {
            dirOk = Directory.Exists(path);
        }
        catch (ArgumentException)
        {
            dirOk = false;//Never gets in here
        }

Edited: Sorry, bad sample path, changed now!

Config VS debugger to halt on all exceptions.VS will break saying: "ArgumentException Occurred" "Illegal characters in path.", but the try catch do nothing.


Edit 2: I think I got it, sorry. VS breaks but the exception is already catch inside Exists().

Upvotes: 0

Views: 417

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273494

The posted code does not throw any exception...

Directory.Exists("nonsense string") just returns false.

As far as I can tell it even returns when the string contains invalid path characters or is null.

On the MSDN page there is no mention of exceptions so I assume this is very 'safe' method to call.

The page does have this to say:

The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Upvotes: 7

HaMster
HaMster

Reputation: 543

Directory.Exists(string path) is not throwing exceptions at all. This seems to be a classic RTFM case ;)

As stated here the method just returns false on any parameter that is not specifying an absolute or relative path.

Upvotes: 1

Swift
Swift

Reputation: 1881

Simply because Directory.Exists does not throw exception when the path is not valid, it only returns true or false depending on the existance of the directory.

Look in the documentation on MSDN

Upvotes: 2

Related Questions