JimDel
JimDel

Reputation: 4359

Two different ways of "catching" two different kinds of exceptions in C#. Is one better than another?

I've never had the need catch more than one exception at a time before. But here's my scenario. I want to "try" to copy a file. If the destination doesn't exist, I don't want to be bothered by it. But I DO still want to catch any other type of exception. A UnauthorizedAccessException for example. Below are two things I've tried, but I've seen both examples used on the web. Is one better coding than another. Or am I completly wrong on both? Thanks.

        catch (DirectoryNotFoundException)
        {
            // Do Nothing
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

or

        catch (Exception ex)
        {
            if (ex is DirectoryNotFoundException)
            {
                // Do nothing
                return;
            }
            else
            {
                MessageBox.Show(ex.Message);
            }
        }

Upvotes: 3

Views: 153

Answers (4)

aL3891
aL3891

Reputation: 6275

The first option is better form, but really they both work equally well.

Go with the first one, it makes for cleaner code

Upvotes: 4

Karthik Mahalingam
Karthik Mahalingam

Reputation: 1071

IMHO, Having multiple catch will reduce the code-readability. So this is what I would like to suggest.

if (Directory.Exists(dirPath))
        {
            try
            {
                File.Copy(sourceFile, destFile);
            }
            catch (Exception msg)
            {
                //Handle Exception.
            }
        }

Upvotes: 5

Tim
Tim

Reputation: 28540

I would go with the first one for 3 reasons:

  1. It reads better (IMO).
  2. I'd be concerned about the overhead of the ex is DirectorNotFoundException statement in the second.
  3. The first one would also be easier to modify - what happens if you have to trap a 3rd type of exception, or a fourth, or...?

Just make sure you catch the exceptions in the right order.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

One advice: never catch an exception which you do not intend to handle:

catch (DirectoryNotFoundException)
{
    // Do Nothing
}

As far as your question is concerned, I would prefer the first approach (assuming of course you know what to do for each exception you have caught).

Upvotes: 3

Related Questions