Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return error and throw exception

Tags:

c#

exception

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

like image 491
gunnerz Avatar asked Aug 17 '12 09:08

gunnerz


People also ask

What is better to throw exceptions or return error codes?

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.

Can you throw an exception and return something?

It's not possible to both throw an exception and return a value from a single function call.

Why is throwing an exception better than returning an error value?

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.


1 Answers

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>.

like image 187
Serg Rogovtsev Avatar answered Nov 09 '22 10:11

Serg Rogovtsev