I have a requirement to throw an exception if I encounter a specific error and return an object in that case.
So I want to do something like this:
if(error)
return obj;
throw new FaultException(string.Format("Error found with ID={0}", ID))
This will not work obviously, as return will prevent the exception from being thrown.
Can anyone suggest whats the best way to achive this. Can I pass the object in the exception somehow?
Thanks
An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call.
It's not possible to both throw an exception and return a value from a single function call.
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code.
Normally you would create your own exception class which would contain all your data. But I see FaultException
which implies WCF, and for that there's already FaultException<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With