Exception

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have a class with a function which returns a string.

However, at the same time I might need to return an error code
(integer).

I need to access this code after calling the function.

How can I do this? Maybe using exception some how?

Thanks,

Miguel
 
Miguel,
You could throw an exeption, but generally that's a bit more
expensive operation and you would have to guarantee being able to catch it
every time. Why not just use an output parameter on the function? This is
done a lot when you need to return more than one value. For example, look at
the int.TryParse() method. It returns a boolean value to say that the string
passed to it is a valid int, and then the second parameter returns an actual
integer value like so:
bool isInteger = false;
string myInt = "1";
int intValue = 0;
isInteger = int.TryParse(myInt, out intValue);
 
The decision between output parameters vs exception isn't generally about
performance, it's about design. They each serve a diferent design.
Int32.TryParse uses an output parameter, and Int32.Parse uses an exception -
they both have different design/purpose.

You should use an exception if the "error code" occurs under truly
rare/unexpected/exceptional situations.

Karl
 
Back
Top