Use TryParse instead of Throwing Exceptions (Try {} Catch {})
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
Related Reading:
Other Interesting Posts
2 Responses to Use TryParse instead of Throwing Exceptions (Try {} Catch {})
Leave a Reply Cancel reply
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta








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.
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.