Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practices when handling Exceptions in C#

I've read in The Pragmatic Programmer, and in some other articles (including one from Joel Spolsky), that you should only throw Exceptions in exceptional cases. Otherwise, you should return an error.

Sometimes it is possible (returning -1, -0, or a positive number, for example), but there are other cases where that is not possible. I mean, if you are returning a class, you can always return null, but I think the idea is to return something that will alert the caller what happened.

If I always return null, I don't think it is useful to say: If this method returns null, it could be because of A, B, C, D, or E

So, how exactly can this be implemented in C#?

Edit:
Hours after I posted this question, I saw another question here where the question itself was about wheter the code posted in was a good practice or not.

I see that is another way of doing what I was asking here. Here is the link:

Generic property disadvantages?

like image 337
Oscar Mederos Avatar asked May 06 '11 21:05

Oscar Mederos


1 Answers

A far better rule for when to throw exceptions is this:

Throw an exception when your method can't do what its name says that it does.

A null value can be used to indicate that you've asked for something that does not exist. It should not be returned for any other error condition.

The rule "only throw exceptions in cases that are exceptional" is unhelpful waffle IMO since it gives you no benchmark to indicate what is exceptional and what isn't. It's like saying "only eat food that is edible."

like image 161
jammycakes Avatar answered Sep 23 '22 06:09

jammycakes