This may be a stupid question, but I’m interested in the performance of using try/catch blocks.
I have a DataGrid that assigns a Converter to the background property of a DataGridCell. In the converter, I compare the value of this year’s data to last year’s data; if this year’s data is > 3%, I return a Green background; if it’s > 0% and < 3%, I return a Yellow; and if it’s < 0%, I return Red:
string x = values[0].ToString().Replace("$", "").Replace(",", ""); //This year's number
string y = values[1].ToString().Replace("$", "").Replace(",", ""); //Last year's
result = (((float.Parse(x) * 100) / float.Parse(y)) - 1) * 100;
if (result >= 3)
return Brushes.LimeGreen;
else if (result >= 0)
return Brushes.Yellow;
else
return Brushes.Red;
However, in some cases, the cell will NOT have a value of last year; as you can guess, dividing by 0 (or some text as the Converter seems to receive when the Cell is empty) is a pretty bad idea and will throw an exception. So, I decided the easiest way to deal with this was:
try
{
result = (((float.Parse(x) * 100) / float.Parse(y)) - 1) * 100;
}
catch
{
return Brushes.DarkOrange;
}
So if the exception is thrown (whereby there is no value to compare to), return an Orange and call it a day. (edit: yes, I do wish to return an Orange when there is no value to compare to.
Currently, I can predict that it will only happen to one row of data for now, so it only catches about 10 cells when it’s populated. But as the future goes on, it has the possibility of having it happen more times.
The try/catch block is the easiest and quickest way to handle this(as far as I can tell), but it is obviously not the only way, especially since I know the error. So Is using a try/catch block a bad idea in this case? And by bad idea, I mean will it slow performance since it is iterated over many, many times? Given that I know what the error will be, should I preempt it, or is using a try/catch block fine?
This is a bad idea. It’s not an exceptional situation, so don’t handle it like it’s one. The fact that you’re worried about performance and exception handling is a smell that you’re doing something wrong. There is a really simple way to handle this, so I don’t even see why you ever thought to instead handle it using exception handling.
Yes, it will impact your performance but that shouldn’t be your concern here. Your concern should be what is the clearest way to write this logic, and using exceptions is clearly not the way.
Here’s that simple way: