List Info

Thread: C-Sharp (C#) Group: try/catch exception and returning values




C-Sharp (C#) Group: try/catch exception and returning values
user name
2006-11-20 18:20:31
Hi everyone!
I'm learning C# and have a part of assignment here that I
can't figure
out. Please help if possible.
I have a form with a couple of text fields and I need to  do
input
validation to make sure that fields are not left blank and
letters
aren't entered isntead of numbers.
The trick is that I MUST do it in a separate BOOL method by
using
try/catch parse.
How do I make this bool method return true if TRY is
successful and
return false if exception is thrown? Something like this
doesnt seem to
work:

private bool isValid(string idOne, string idTwo)
{
 try
 {
  int id1=int32.parse(idOne);
  int id2=int32.parse(idTwo);
  return true;
 }
 catch ( exceptionname error)
 {
  messageBox.show( "Error: " + error);
  return false;
 }
}

private main(.....
{
 if (isValid( txtId1.Text , txtId2.Text)==true)
   asnwer.Text="awsome";
 else
  answer.Text="this sucks";
}


--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the
Google Groups "C-Sharp (C#)" group.
To post to this group, send email to C_Sharpgooglegroups.com
To unsubscribe from this group, send email to
C_Sharp-unsubscribegooglegroups.com
For more options, visit this group at htt
p://groups-beta.google.com/group/C_Sharp?hl=en
-~----------~----~----~----~------~----~------~--~---

C-Sharp (C#) Group: Re: try/catch exception and returning values
user name
2006-11-20 19:16:49
Try putting "return true" after the catch block.  It would like this after making that change:
 
private bool isValid(string idOne, string idTwo)
{
try
{
int id1=int32.parse(idOne);
int id2=int32.parse(idTwo);
}
catch ( exceptionname error)
{
messageBox.show( "Error: " + error);
return false;
}
return true;
}

You might get some folks telling you not to verify the validity of input like this, but I wouldn't worry about it too much. ; If you had a method that could be called potentially thousands of times, then yeah you should look into something like RegEx or int.TryParse(if .NET 2.0) for your validation.  The reason being is that exceptions are fairly expensive performance-wise.

--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the Google Groups "C-Sharp (C#)" group.
To post to this group, send email to C_Sharpgooglegroups.com
To unsubscribe from this group, send email to C_Sharp-unsubscribegooglegroups.com
For more options, visit this group at http://groups-beta.google.com/group/C_Sharp?hl=en
-~----------~----~----~----~------~----~------~--~---

[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )