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?
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());
…}
}
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.