Tuesday, September 12, 2006

Try.Catch. is not a good Practice

I don’t know using try catch in your code is good or bad. But I am sure that it makes your code run more slowly. For the early edge of my programming carrier I believed that c# language has managed the try catch or exception handling quite well. So we can use try catch as much as we can in our code to deal with the exception. But while working on the International Tax Expert project I found try catch is making my program working slow... this happens specially in paring a string to integer.

Let say

We have a code portion like

bool IsValidInteger(string s)
{
try
{
int x = int.parse(s);
return true;
}
catch
{
return false;
}
}


If we manage to provide an invalid string which is not an integer the program returns the accurate value that is false. And for only one case this works fine and no performance degradation occurs.

But if we have to fill a data grid which has 1000 rows and one columns value is filed using the above mentioned function to show an icon or assign formatting for the data to show on the cell. The performance hit shows, and the program run slow.

So it is better to avoid “try catch” as much as you can in your code, there is always a good way to code such things. We should always remember coding is also an art and we can make it stylish.

Our senior software Engineer Hasan Shahriar Masud provided a good example on this matter the example is given bellow.

“We should not use try-catch if we can logically conclude the exception. It will help the performance, which munna(that is me) proved.

For example


//We should not write
Try
{
C=A/B;
//Do Something 1
}
Catch
{
//Do Something 2
}
//We should write
If (B==0)
{
Do Something 2
}
Else
{
C=A/B;
//Do Something 1
}

I have investigated this on Xceed grid 3.1 in case of data convertion. May be its a problem of xceed grid.

Xceed Grid 3.1 very cool data grid component

Recently in our project we have started to use xceed grid 3.1. Well xceed is very smart to introduced few new features.
Two most interesting features that impressed me is xceed grid report features. and its fixed column feature. this two feature is badly needed in our project . thanks to xceed that the reporting now easy like ice-cream.
let me give you an example how easy its is to create a report from a grid.

using( GenerateReportForm generateReportForm = new GenerateReportForm( this.gridControl1 ) ) 
{
enerateReportForm.ShowDialog( this );
}



Very easy . and the fixed column feature is more easy all you have to do is to set a property of the column. that the property is "isFixed"