ASP Try...Catch Question

I’ve got a do loop

example:
Do While X < 20
…A lot of code
Loop

Now, I need to catch an error if X cannot be converted to a numeric value. However, I do not want to catch anything else in the Do loop (which may include the same class of error). Is there a way to accomplish this?

What kind of data type is X? A variant or an object or something?

An easy way to do something like this is to include a try/catch before the loop. Something like:

try
{
}

What kind of data type is X? A variant or an object or something?

An easy way to do something like this is to include a try/catch before the loop. Something like:

try
{
int y = x; //this will error out if x can’t be converted

}
catch (Exception exp)
{
throw (new MyCustomException());

}

Mods, mind removing my fat finger half reply up above? Thankee!

X is from a COM object (actually it is the value of one cell of a spreadsheet), and it may or may not be valid each time I go through the loop.

So, I guess I could do:

try
{
…int y = x; //this will error out if x can’t be converted
}
catch (Exception exp)
{
…throw (new MyCustomException());
}

while (y <20)
{
…//Do what I need to do here


…try
…{
…int y = newx; //this will error out if x can’t be converted
…}
…catch (Exception exp)
…{
…throw (new MyCustomException());
…}
}

(sorry if my C# skills are lacking.

Are you using ASP.NET or classic ASP? If ASP.NET then try Athena’s solution, but for the old-fashioned style of ASP this might work (can’t guarantee cause I’ve only got ASP.NET now):

Do While X < 20
…If Not IsNumeric(X) Then
… ’ Handle the Error
…Exit Do
…Else
…A lot of code
…End If
Loop

By the look of your example code you’re using VB.Net. In this case it’d be best to test the variable X before using it in the loop. VB has the IsNumeric function, but this may not be specific enough for you since it will return true if the variable can be converted into an integer, double, single etc.

The most precise way of dealing with it would be to declare another variable and do a type-specific conversion inside a catch:



Dim iX as Integer
Try
    iX = Integer.Parse(X)
Catch e As Exception
    ' Do whatever you need to here when it won't convert
End Try


This example is if you expect X to be an Integer, but it will be similar for other numeric types.

If you’re using the 2.0 framework then there is a final CanParse (or similar, my memory fails me) method on the value class that will tell you whether the input is in the correct format.

Yes, I am using ASP.NET w/ VB.NET 1.1.

The problem with just doing the try catch block before the loop is that the value changes each time. What I’m going to try now:

If Double.TryParse(X) Then
…Do While X < 20
…do something

…Do While Not Double.TryParse(X)
…change the value of X
…Loop
…Loop
End If