I have read in many places that try...catch is a means of detecting
errors but it shouldn't be used if you know the error might occur.
Rather you should use other means to detect the condition.
Try...catch is for errors you don't know are going to occur (bugs) to
keep your application behaving nicely.
Your point of don't fix it unless it is broken is well taken, but I
feel this will be an issue for us and should be addressed through some
other means.
We are exploring the use of regular expressions to validate the input
before we attempt to cast it as a date.
On Tue, 07 Sep 2004 12:53:57 -0700, Julie <ju***@nospam.com> wrote:
John Livermore wrote:
In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?
Is there a particular reason that you can't use try/catch?
Here is what I know I can use, but there are potentially thousands of
dates to validate, and
I know this code is inefficient if there are
lots of dates that won't convert...
How do you know it is inefficient?
Do you have specific performance requirements that aren't being met? If not,
don't worry about the performance.
The first rule of optimization is: don't do it.
private DateTime ValidateDate(string date)
{
DateTime convertedDate = DateTime.MinValue;
try
{
convertedDate = DateTime.Parse(date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}