Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to return from a failed method and when to throw?

Tags:

c#

.net

I´ve lately been thinking about the things i´m returning from methods and I noticed that there are 4 different things i return when the method fails.

What bothers me about it, is that my code is not very consitent in this regard, so i wanted to ask about your "best practices".

So lets imagine a method that takes Foo and returns a list of Bar:

public IList<Bar> Method(Foo something);

Or to keep it more general:

public IBar Method(IFoo something);

The question is what do you return on what kind of failure. the options would be:

  1. empty return type like: new List; or: new EmptyBar();
  2. null
  3. throw an exception
  4. a special list value indicating failure like: new List{new FailureBar()}

I really hate option 4 so I´m mostly interessted to hear when you use the other 3 options and why

like image 645
LDomagala Avatar asked Apr 06 '09 10:04

LDomagala


People also ask

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.

What does method return if exception is thrown?

Does throwing an exception within a method cause the method to return? Yes. Execution of a method is being interrupted, so method returns it execution flow.

Should I return after throw?

You do not need to put a return statement after throw , the return line will never be reached as throwing an exception immediately hands control back to the caller.

Is throwing an exception the same as returning a value?

For example Note that throwing an exception means that the method was used wrong or had an internal error, while returning an exception means that the error code was identified successfully.


1 Answers

I'd choose between an empty list and an exception depending on the nature of the failure.

E.g.

If your database failed to connect - exception.

If your query didn't return results - empty list.

like image 79
Rob Stevenson-Leggett Avatar answered Sep 29 '22 23:09

Rob Stevenson-Leggett