Alternative to try / catch?

G

Guest

I want to convert a string to a DateTime type. The user can enter the date in
various formats and I am not sure if it will be a valid Date. Is it possible
to check if a string can be converted to a DateTime type without using a try
/ catch block. I was thinking of maybe something like is or as commands. But
both do not seem to work for this. Any suggestions will be much appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net ver
1.1

Thanks in advance.
 
N

Nicholas Paldino [.NET/C# MVP]

Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course, you
want to parse the format yourself. However, I think that the try/catch is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.
 
G

Guest

Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime are
in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course, you
want to parse the format yourself. However, I think that the try/catch is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tantr Mantr said:
I want to convert a string to a DateTime type. The user can enter the date
in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using a
try
/ catch block. I was thinking of maybe something like is or as commands.
But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net ver
1.1

Thanks in advance.
 
J

Jeff Shepler

If try/catch is slowing you down, you are probably running your code
through the debugger (pressing F5 for example).

Here's a good read about exceptions and performance:

http://www.yoda.arachsys.com/csharp/exceptions.html




Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime are
in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course, you
want to parse the format yourself. However, I think that the try/catch is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tantr Mantr said:
I want to convert a string to a DateTime type. The user can enter the date
in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using a
try
/ catch block. I was thinking of maybe something like is or as commands.
But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net ver
1.1

Thanks in advance.
 
N

Nicholas Paldino [.NET/C# MVP]

Tantr,

You could use a Regex, but I have to say, I really think that you
should stick with the try/catch, as it's the difference between maintaining
a few lines of code, versus a lot more.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tantr Mantr said:
Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime
are
in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course,
you
want to parse the format yourself. However, I think that the try/catch
is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tantr Mantr said:
I want to convert a string to a DateTime type. The user can enter the
date
in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using
a
try
/ catch block. I was thinking of maybe something like is or as
commands.
But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be
something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net
ver
1.1

Thanks in advance.
 
J

Jon Skeet [C# MVP]

Tantr said:
Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime are
in a Column of a grid , so called multiple times.

Just how many elements are in this grid? In release mode, exceptions
are incredibly quick, despite the misinformation to the contrary.
Unless you've got thousands and thousands of invalid dates, it's
unlikely to be causing a significant loss in performance except in the
debugger.

See http://www.pobox.com/~skeet/csharp/exceptions.html for more on
this.

Jon
 
G

Guest

A regular expression can't catch every illegal date, but it can very
well be used to verify that it at least looks like a date. You can
verify that the month is in the range one to twelve, and that the day is
in the range one to 31.

You can use the regular expression to get the year, month and day from
the string. Use the Calendar.GetDaysInMonth method to get the number of
days in that month and compare it to the day value that you have. This
way you can validate the date without using exceptions.

I checked this code for speed:

GregorianCalendar calendar = new GregorianCalendar();
Regex verify = new
Regex(@"^(0[1-9]|[1-2]\d|3[0-1])/(0[1-9]|1[0-2])/(\d\d\d\d)$",
RegexOptions.Compiled);
for (int i = 0; i < 1000000; i++) {
string date = "14/12/2006";
Match match = verify.Match(date);
if (match.Groups.Count == 4) {
int year = int.Parse(match.Groups[3].Value);
int month = int.Parse(match.Groups[2].Value);
int day = int.Parse(match.Groups[1].Value);
if (day <= calendar.GetDaysInMonth(year, month)) {
DateTime theDate = new DateTime(year, month, day);
}
}
}

It parses a million dates in three seconds, and discards a million
incorrectly formatted dates in half a second.

The I compared it to this code:

for (int i = 0; i < 1000000; i++) {
string date = "12/13/2006";
try {
DateTime theDate = DateTime.ParseExact(date, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
} catch (Exception ex) {
}
}

It parses a million dates in just one second, but a million incorrect
dates takes 60 seconds to handle.


Tantr said:
Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime are
in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course, you
want to parse the format yourself. However, I think that the try/catch is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tantr Mantr said:
I want to convert a string to a DateTime type. The user can enter the date
in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using a
try
/ catch block. I was thinking of maybe something like is or as commands.
But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net ver
1.1

Thanks in advance.
 
G

Greg Young

This is why the TryParse pattern is used in 2.0.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

Göran Andersson said:
A regular expression can't catch every illegal date, but it can very well
be used to verify that it at least looks like a date. You can verify that
the month is in the range one to twelve, and that the day is in the range
one to 31.

You can use the regular expression to get the year, month and day from the
string. Use the Calendar.GetDaysInMonth method to get the number of days
in that month and compare it to the day value that you have. This way you
can validate the date without using exceptions.

I checked this code for speed:

GregorianCalendar calendar = new GregorianCalendar();
Regex verify = new
Regex(@"^(0[1-9]|[1-2]\d|3[0-1])/(0[1-9]|1[0-2])/(\d\d\d\d)$",
RegexOptions.Compiled);
for (int i = 0; i < 1000000; i++) {
string date = "14/12/2006";
Match match = verify.Match(date);
if (match.Groups.Count == 4) {
int year = int.Parse(match.Groups[3].Value);
int month = int.Parse(match.Groups[2].Value);
int day = int.Parse(match.Groups[1].Value);
if (day <= calendar.GetDaysInMonth(year, month)) {
DateTime theDate = new DateTime(year, month, day);
}
}
}

It parses a million dates in three seconds, and discards a million
incorrectly formatted dates in half a second.

The I compared it to this code:

for (int i = 0; i < 1000000; i++) {
string date = "12/13/2006";
try {
DateTime theDate = DateTime.ParseExact(date, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
} catch (Exception ex) {
}
}

It parses a million dates in just one second, but a million incorrect
dates takes 60 seconds to handle.


Tantr said:
Many Thanks Nicholas! How do I parse the Format myself? Should I be
looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime
are in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course,
you want to parse the format yourself. However, I think that the
try/catch is better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

I want to convert a string to a DateTime type. The user can enter the
date in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using
a try
/ catch block. I was thinking of maybe something like is or as
commands. But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be
something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net
ver
1.1

Thanks in advance.
 
J

Jeff Shepler

On my dated server, it took 2.08 seconds to parse a million dates and
discarded a million in 68.03 seconds.

I tried .net 2.0's TryParse() for comparison. It parsed a million
dates in 2.09 seconds and discarded a million in 2.63 seconds!!



A regular expression can't catch every illegal date, but it can very
well be used to verify that it at least looks like a date. You can
verify that the month is in the range one to twelve, and that the day is
in the range one to 31.

You can use the regular expression to get the year, month and day from
the string. Use the Calendar.GetDaysInMonth method to get the number of
days in that month and compare it to the day value that you have. This
way you can validate the date without using exceptions.

I checked this code for speed:

GregorianCalendar calendar = new GregorianCalendar();
Regex verify = new
Regex(@"^(0[1-9]|[1-2]\d|3[0-1])/(0[1-9]|1[0-2])/(\d\d\d\d)$",
RegexOptions.Compiled);
for (int i = 0; i < 1000000; i++) {
string date = "14/12/2006";
Match match = verify.Match(date);
if (match.Groups.Count == 4) {
int year = int.Parse(match.Groups[3].Value);
int month = int.Parse(match.Groups[2].Value);
int day = int.Parse(match.Groups[1].Value);
if (day <= calendar.GetDaysInMonth(year, month)) {
DateTime theDate = new DateTime(year, month, day);
}
}
}

It parses a million dates in three seconds, and discards a million
incorrectly formatted dates in half a second.

The I compared it to this code:

for (int i = 0; i < 1000000; i++) {
string date = "12/13/2006";
try {
DateTime theDate = DateTime.ParseExact(date, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
} catch (Exception ex) {
}
}

It parses a million dates in just one second, but a million incorrect
dates takes 60 seconds to handle.


Tantr said:
Many Thanks Nicholas!
How do I parse the Format myself? Should I be looking at Regex?
Its just that the Try/catch is making the app quite slow as the DateTime are
in a Column of a grid , so called multiple times.

Cheers!

Nicholas Paldino said:
Tantr,

Other than using a Try/Catch, there isn't a way. Unless of course, you
want to parse the format yourself. However, I think that the try/catch is
better in terms of maintainability.

When you move to .NET 2.0, you can use the TryParse method on the
DateTime structure.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

I want to convert a string to a DateTime type. The user can enter the date
in
various formats and I am not sure if it will be a valid Date. Is it
possible
to check if a string can be converted to a DateTime type without using a
try
/ catch block. I was thinking of maybe something like is or as commands.
But
both do not seem to work for this. Any suggestions will be much
appreciated.

Right now i have :
string s = "01/05/2006"; //user will be entering the data ,
//this could be something
invalid like 22/22/2006
try
{
DateTime dt = DateTime.Parse(s);
MessageBox.Show("Date Parse Ok!");
//..other processing
}
catch(FormatException formatEx)
{
MessageBox.Show(formatEx.Message);
}


I was thinking of something along the lines :

if(s is DateTime)
MessageBox.Show("Date !!!");
else
MessageBox.Show("String...");

but this does not work as C# always considers s to be of type string.
Is there any way of not using the try / catch block? I am using .Net ver
1.1

Thanks in advance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top