I've been refactoring code over the last few days and have begun to see a recurring anti-pattern to blog about; the try-catch-eat anti-pattern. This pattern is possible in many languages (C#, C++, VB.NET, Java, Javascript, Ruby and newer T-SQL).
It goes something like this (pseudo-C#):
try
{
//do some work here
}
catch
{
//eat the exception
}
The most recent example of this occurred where code was converting a C# decimal value to a double value using the decimal.ToDouble(); nevermind for a second that MSDN's documentation on the Decimal structure states: "The conversion will not throw an exception.". :)
The fun thing about this pattern is its portability; e.g. one could can implement it in a for-loop, used nested if statements. e.g.
if (/* some logical test; code changed to protect the guilty*/)
{
foreach (/* some looping variables here; code changed to protect the guilty */)
{
try
{
if (/* some logical test; code changed to protect the guilty*/)
{
foreach (/* some looping variables here; code changed to protect the guilty */)
{
try
{
if (/* some logical test; code changed to protect the guilty*/)
{
foreach (/* some looping variables here; code changed to protect the guilty */)
{
try
{
if (/* some logical test; code changed to protect the guilty*/)
{
double d = decimal.ToDouble(someDecimalValue);
}
}
catch (Exception) {}
}
}
}
catch (Exception) { }
}
}
}
catch (Exception) { }
}
}
Now, to be fair, I know we all rush through from time-to-time and write poor quality code when we're under the gun. Unfortunately that was not the issue (this part of the project schedule has actually been pretty sane).
One potential exception to this is if you're writing a function in C# like IsDate, e.g.
public static bool IsDateEx(string s)
{
try
{
return DateTime.Parse(s);
}
catch
{
//eat it?
}
}
maybe you could get away with this.
If you were in .NET 2.0 you could use the TryParse method and avoid the try-catch-eat altogether:
public static bool IsDate(string s)
{
DateTime result;
return DateTime.TryParse(s, out result);
}
Development is a funny thing; often there are no absolute truths and we have to measure things by being better or worse (kind of like the eye doctor!). Implementing the try-catch-eat anti-pattern is a lazy development practice which leads to poor quality code and should be avoided when possible.
jk