I noticed something in the code of the project I was currently working on. It manifested itself in a crash with exception type FormatException. The problem was caused by the developer using code like this:

double percentComplete = Convert.ToDouble(tbProgress.Text);

or

double percentComplete = double.Parse(tbProgress.Text);

The problem with this is that there are potential exceptions lurking if the string value is null or malformed (which was the case)

Instead of just coding like the above the developer should have at least tried to catch the exception like so and handle it (in this case it was best to give back a default value of 0):


double percentComplete;
try
{
    percentComplete = double.Parse(tbProgress.Text);
}
catch (FormatException)
{
	// Handle the error or return a default value
    percentComplete = 0;
}

To be an good developer you should use TryParse instead

double percentComplete = 0;
if (!double.TryParse(tbProgress.Text, out percentComplete))
{
    // Handle the error
}

In the situation above, I didn’t need to handle the error as I wanted to return a default value of 0 if it couldn’t parse it. So the following would have sufficed:

double percentComplete = 0;
double.TryParse(tbProgress.Text, out percentComplete);

Why is TryParse better?

Remember, exceptions are expensive to deal with. So avoid it if you can.

Other resources

Comment