Question
I have some code which ignores a specific exception.
try
{
foreach (FileInfo fi in di.GetFiles())
{
collection.Add(fi.Name);
}
foreach (DirectoryInfo d in di.GetDirectories())
{
populateItems(collection, d);
}
}
catch (UnauthorizedAccessException ex)
{
//ignore and move onto next directory
}
of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning?
Solution
Just rewrite it as
catch (UnauthorizedAccessException) {}
OTHER TIPS
As Dave M. and tvanfosson said, you want to rewrite it as
catch (UnauthorizedAccessException) {}
The bigger question that should be asked, however, is why you are catching an exception on ignoring it (commonly called swallowing the exception)? This is generally a bad idea as it can (and usually does) hide problems in the application at runtime that can lead to very strange results and a difficult time debugging them.
I usually do
Debug.WriteLine(ex.message)
(that way I can just set a breakpoint in the exception, if needed, too)
Assuming the comment in your original code is an accurate description of what you're trying to do, I think you want to write it like this:
foreach (FileInfo fi in di.GetFiles())
{
//TODO: what exceptions should be handled here?
collection.Add(fi.Name);
}
// populate collection for each directory we have authorized access to
foreach (DirectoryInfo d in di.GetDirectories())
{
try
{
populateItems(collection, d);
}
catch (UnauthorizedAccessException)
{
//ignore and move onto next directory
}
}
And then you need to work on that TODO item.
I agree with the people who say it's probably a bad idea to simply ignore the exception. If you're not going to re-throw it then at the very least log it somewhere. I've written small tools that process a list of files where I didn't want errors on individual files to crash the whole program, and in such cases I would print a warning message so I could see which files were skipped.
The only time I personally ever catch an exception without naming it, as in catch(xxxException), is if I'm going to react to it in some way and then re-throw it so that I can catch it in some outer routine. E.g.:
try
{
// do something
// ...
}
catch(UnauthorizedAccessException)
{
// react to this exception in some way
// ...
// let _someone_ know the exception happened
throw;
}
Even though I'm a Java developer (not C#), @Scott Dorman is absolutely right. Why are you "swallowing the exception"? Better yet, what could throw the UnauthorizedAccessException? Here are common-sense possibilities:
- The file doesn't exist
- The directory doesn't exist
- The current thread of control does not have the correct security privileges. In the *nix world, the current thread may be in the wrong group or the wrong user.
- The disk crashed
- The file's ACL is set to write only but not read. Likewise, for the directory.
The above of course is an incomplete list.