Use TryParse instead of Throwing Exceptions (Try {} Catch {})

May 25th, 2007 by Sameer | Filed under .NET articles.
How to use TryParse with examples (Int32.TryParse, Double.TryParse, etc)

Exceptions should be left for exceptional circumstances.  We should not be using exceptions to control the flow and logic of our application. 

Exceptions are much more expensive to handle ,and are not meant to control the flow of your application.  If you are using a try catch block in order to convert a string to an int, you can completely avoid the exception by using TryParse.

TryParse was was added to .NET 2.0 specifically so that we could avoid this situation. If you have some .NET 1.0 code, you might not be taking advantage of .NET 2.0 new TryParse functions, which avoid exception handling and are much faster.

 

For example:

try
{
    iEditMode = Convert.ToInt32(strEditMode);
}

catch
{
    iEditMode = 0;
}

In this case, we have TryParse functions which were added in .NET 2.0
Better to instead do:

if (!Int32.TryParse(strEditMode, out iEditMode))
{
    iEditMode = 0;
}

Much better performance, no need to handle clunky exceptions :) Thank you to Brendan for correcting my error above. (missing out keyword)

MSDN in regards to exception handling states, "Do not use exception handling for flow of control, only for failure situations."

Resources 

Other Interesting Posts

2 Responses to “Use TryParse instead of Throwing Exceptions (Try {} Catch {})”

  1. Ingvar says:

    The example is confusing, because it may let us believe that the out-parameter is unchanged when conversion fails.

    But when TryParse returns, the out parameter is zero if the conversion failed.

    So if you want iEditMode = 0 when the conversion fails you may just write
    Int32.TryParse(strEditMode, out iEditMode)
    with no check on the return value.

  2. You are right, Thank you. Setting iEditMode = 0 inside the curly braces is not a good example. Better to do something else inside the braces such as output something or disable buttons or whatever is needed.

Leave a Reply