Re: methods and returned values
Efran Cobisi <[email protected]> Fri, 27 Oct 2006 17:27:50 +0200
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Organization | QBGROUP SpA |
| Message-ID | <[email protected]> |
Hi,
IMHO there are two possible solutions to this design problem:
a) Instead of calling the private method which throws the exception in
the aforementioned else block, wrap all of the checks you make in the
other methods inside the private one. Then just call the private method
before the if block, which in turns you should be able to remove.
void VerifyCanReturnMyObj()
{
bool bVerified = false;
// TODO: Check the conditions...
if (!bVerified)
throw new MyCustomException();
}
MyObj MethodA()
{
VerifyCanReturnMyObj();
// ...
return new MyObj();
}
b) Don't call the private method to throw the error. Just thows it in
the else block; the compiler is smart enough to understand the code path
is correct.
MyObj MethodA()
{
if (...)
return new MyObj();
else
throw new MyCustomException();
}
HTH
Efran Cobisi, cobisi.com
Peter Osucha wrote:
> OK - sorry for the dumb question but...
>
> I have a bunch of methods that are set up to return values of type MyObj.
> In virtually all of the methods, there is an if...else construct so that if
> a condition isn't met for returning a valid MyObj, a derived exception can
> be raised with info as to what the problem was.
>
> So I decided to create a private method that would generate the exception
> and then throw it which I would call from the 'else' block of all the
> methods described above. This isn't legal, however, since I then get an
> error that not all code paths return a value (namely, the 'else' block which
> call the private method to throw the error.
>
> What is the best way around this (besides duplicating all the code to create
> and throw the derived exception in each of the methods)?
>
> Peter
>
> ===================================
> This list is hosted by DevelopMentor® http://www.develop.com
>
> View archives and manage your subscription(s) at http://discuss.develop.com
>
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com