Welcome to AspAdvice Sign in | Join | Help

Use .TryParse instead of Try {} Catch {}

In certain conditions, we should not be using exceptions.  For example, Try Catch blocks can be avoided in certain cases.  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 

Sponsor
Published Tuesday, May 15, 2007 3:25 PM by salibhai
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Use .TryParse instead of Try {} Catch {}

Wednesday, May 16, 2007 9:21 AM by Brendan
Actually that is not quite correct. You need to do this instead if (!Int32.TryParse(strEditMode, out iEditMode)) { iEditMode = 0; } The reason you need the out keyword is because the second argument you pass is a special parameter for this method. "out" signals that the parameter is going to be initialized to a value by the function. I am pretty sure you'll get a compiler error doing it the way you've said here.

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below