Reputation: 4359
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
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
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
Reputation: 28540
I would go with the first one for 3 reasons:
ex is DirectorNotFoundException
statement in the second.Just make sure you catch the exceptions in the right order.
Upvotes: 3
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