Continue execution after exception?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm writing a simple application that deletes multiple directories. I want
to write it so that it will simply continue on through the list of
directories if an exception is thrown (the directory is not there). Is there
a way to do this? Am I approaching this all wrong?
 
You can use Directory.Exists(path) to test if a directory exists before
trying to access objects in it, thereby avoiding an exception in the 1st
place.
Other then that, you can use...
foreach ( string directory in Directory.GetDirectories(filter) )
{
try
{
// code that accessses the directory
}
catch(Exception ex)
{
// this output is optional - there are many other things you can do here
Debug.WriteLine("Error accessing directory.\n" + ex.Message);
}
}

and execution will continue after spitting out the debug trace.

I suggest NOT doing it this way...the real question is what would you be
doing that incurs an exception? If you can avoid it you are better off doing
so.
 
Catch and discard the exception. At its simplest:

try
{
// do your stuff here.
}
catch ( SomeExpectedTypeOfException e )
{
// but don't do anything with it.
}

It would be wise to explicitly catch and discard only the specific exception
types you're willing to ignore. Other types of exceptions might be
legitimate, and you may want to catch them as well and handle them in other
ways (a Permissions exception, for instance, is a show-stopper). But there's
no reason why you can't continue processing in your method, regardless of
the exceptions you catch, as long as you don't rethrow the exception in the
catch block. Remember to order your catch clauses in order of most-specific
exception type to least specific.

HTH,
Tom Dacon
Dacon Software Consulting
 
Handle exceptions in a loop (like for each or so)...so after the exception is
caught and you handle it, the next iteration would start and it would go on
and on....
 
Back
Top