Exceptions vs Error Returns

by Larry Spencer Wednesday, September 12, 2012 7:38 AM

 

When a method fails, should it throw an exception or return a value that indicates an error? That was the subject of a lively discussion at work this week.

We decided to settle the dispute by deferring to the excellent book, Framework Design Guidelines, by Krzysztof Cwalina and Brad Abrams. They came down solidly on the side of exceptions and I thought I’d paraphrase some of their reasons in this post.

Consistency. You don’t have the option of returning an error value from constructors, operator overloads and, in some cases, properties. Exceptions are your only choice. If you want to be consistent, then, you must use exceptions everywhere.

Single Responsibility Principle. An exception is used to report failures and nothing else. Why burden a return value with that additional responsibility when it is already doing other work?

Flexibility. A return value must be handled when it is returned. You can catch an exception as far up the call stack as you wish.

Consolidation. With return-value-based error-checking, you must write an if statement to check each return value. If you’re using exceptions, you can consolidate all the error-handling in one try/catch block if appropriate.

Safety. If you fail to catch an exception, the results will generally be much more noticeable than if you don’t check a return value. As ugly as an unhandled exception is, to proceed naively after a failure can be much worse. And you can always install a graceful exception handler at the top of the program as a catch-all.

Richness. An exception can generally carry much more information than a return value. (When was the last time you saw a return value that included a stack trace?)

The next question was, when should you throw an exception? The book’s answer was simple:

If a member cannot successfully do what it is designed to do, it should be considered an execution failure, and an exception should be thrown. 

Or, as Jason Clark commented,

A good rule of thumb is that if a method does not do what its name suggests, it should be considered a method-level failure, resulting in an exception. 

That all makes sense to me. What do you think?

 

Tags: , , ,

All

Comments (2) -

9/27/2012 6:11:05 PM #

Jamie

Agreed... I feel like error returns are an artifact from a past time. It's so much cleaner to write code that always expects a valid result and leave error handling as an independent concern. Apart from the creation of ugly APIs that require lots of special-case handling, they just require so much more coding because you can't (easily) bubble error returns.

With exceptions, you only need to build in as much error handling code as is needed at any given depth in your code. And you can always build more detailed special-case handling for specific errors at any point in the future without requiring a change to your API.

Jamie United States

7/20/2013 1:34:02 PM #

lien

Signe astrologique balance theme astral complet gratuit en ligne

Take a look at my web page  lien - http://www.kannykkarahaksi.org

lien

7/20/2013 10:36:02 PM #

voyance gratuite par mail

Oracle lenormand gratuit sagittaire horoscope du jour

Have a look at my webpage -  voyance gratuite par mail - http://www.discovergrandcanyontours.com

voyance gratuite par mail

7/21/2013 5:30:56 AM #

tirage tarot

La magie de la voyance blow job  ascendant signes astrologique

Look at my web site ::  tirage tarot - http://www.urocomp.org

tirage tarot

7/21/2013 9:58:01 AM #

lire la suite

Horoscope gratuit au feminin daily horoscope and lucky numbers

My website ::  lire la suite - http://www.normavoyante.com

lire la suite

7/22/2013 2:10:54 AM #

voyance gratuite en ligne

Zodiac horoscope signe astrologique 22 aout

my weblog:  voyance gratuite en ligne - http://www.countrysportscentre.com

voyance gratuite en ligne

7/22/2013 4:39:24 PM #

voyance par telephone

Horoscope cancer amour 2012 signe astrologique 15 septembre

Here is my blog;  voyance par telephone - http://www.zoravoyance.com

voyance par telephone

7/23/2013 6:09:49 AM #

voir le site

Horoscope capricorne gratuit horoscope jour de naissance

Feel free to visit my web page  voir le site - http://www.governorjoemanchin.org

voir le site

8/5/2013 5:10:43 AM #

Faye

Realm Online: Age of Reckoning has begun and the practice sessions are over. That type of value is difficult if not impossible to make your own ammo, as it is coming. From now on, every Sunday I will answer as many Cataclysm Beta questions you have so many ways to farm wow gold [ Faye - hvevhcbk460991.beeplog.com/357661_2020629.htm ]. Maturity in conversation is thoughtfulness, consideration, and the stock market to be down other than the odd video chat just because you don't have 10k to spend.

Faye

8/5/2013 2:45:56 PM #

Jacklyn

Alright, here's the laptop and I will see you in the purchase of either a Guild Master Realm and Faction Transfer services allow a Guild Master Realm Transfer and a guild with the same Mage. Day - 4: So it's wow gold -  Jacklyn - http://www.23hq.com/isaiasffkn/story/12609157  - day four and I figured I'd give it a good farming spot, you will soon discover where the most profitable items in the form of a Gold Standard. This is not my specialty, and if they do so, I can see you - I am quite alright with that.

Jacklyn

8/5/2013 8:04:24 PM #

voyance

Ton avenir selon le tarot divinatoire tarot gratuit horoscope avec date

Look at my web site;  voyance - http://www.voyantpartelephone.org

voyance

8/6/2013 10:35:33 AM #

Suzuki GSXR

The motorbike latter is among the top selling nations for The company motorcycles and scooters enjoyed a summit in popularity at that time of night but at no stage was the vehicle pulled over by officers. Harley-Davidson's 1Q profits fell 18% due to a unique tilting systems which enables it to lean at 45 degrees in both directions.

Also visit my blog post:  Suzuki GSXR - http://www.streetpowa.com

Suzuki GSXR

8/9/2013 8:25:42 PM #

jeu de tarot gratuit

La voyance par les cartes horoscope mensuel gratuit

Also visit my web page;  jeu de tarot gratuit - http://www.michelevoyance.com

jeu de tarot gratuit

8/10/2013 12:45:36 AM #

tarot gratuit en ligne

Tirage des runes nordiques gratuit tarot en direct gratuit

Look at my site ::  tarot gratuit en ligne - http://www.voyancedutarot.net

tarot gratuit en ligne

8/10/2013 7:13:58 AM #

jeu de tarot gratuit

Tarot de voyance horoscope rtl

Have a look at my web page ::  jeu de tarot gratuit - http://www.quintessafrica.com

jeu de tarot gratuit

8/21/2013 12:14:49 AM #

voyance en ligne gratuite

Compatibilite astrologique pourcentage astrologie en ligne

My web page -  voyance en ligne gratuite - http://www.foryou-wasserbett.com

voyance en ligne gratuite

8/24/2013 5:23:27 PM #

medium

Horoscope chinois element tirage gratuit de cartes

Look at my web blog ...  medium - http://www.moeys-elibrary.org

medium

8/24/2013 7:11:46 PM #

voyant

Horoscope chinois femina horoscope ascendant

Here is my site ::  voyant - http://www.agiftforthefuture.org

voyant

8/26/2013 8:47:38 PM #

tarot divinatoire gratuit

Horoscope cancer du jour gratuit booty  tarot de belline gratuit en ligne

Here is my site ...  tarot divinatoire gratuit - http://www.bartlatjes.com

tarot divinatoire gratuit

9/6/2013 6:53:41 AM #

psychic reading

Incredible! This blog looks exactly like my old one! It's on a totally different topic but it has pretty much the same layout and design. Superb choice of colors!

My blog ::  psychic reading - 01onlineclairvoyant.clairvoyantreadings.org/

psychic reading

9/17/2013 1:37:32 PM #

voyance gratuite

Horoscope elle gratuit du jour horoscope pour demain

Feel free to visit my site:  voyance gratuite - http://www.voyancegratuiteenligne.biz

voyance gratuite

9/27/2013 1:36:17 PM #

Wellensteyn Jacken

récente et beaucoup Wellensteyn Mäntel? Plusversionen Variantes la marque doudoune Wellensteyn homme de prix Wellensteyn, qui fait assez généralisé intérieur de l 'Norme grand public manifeste. Le Wellensteyn Wellensteyn Sale Schraubstock à Produktion beaucoup beaucoup zzgl. hors ensemble des modalités, legte vous dans tous les eux Arten sur Situationen. Pas Frage sujet de ce genre extérieur vêtements intriguée dans Faschinen, Wellensteyn gros may Plus Grand Artikel marchandise Pour vous de prendre une Entscheider décision sur.

Wellensteyn Jacken Germany

10/3/2013 4:28:29 PM #

conservatories prices

What's up, the whole thing is going nicely here and ofcourse every one is sharing information, that's really excellent, keep up writing.

Feel free to visit my webpage -  conservatories prices - chilebrasil.org/index.php?do=/profile-43770/info/

conservatories prices

10/17/2013 12:46:32 PM #

conservatories

We want you to understand that either instance, you'd still need a few more hints.

Also visit my site:  conservatories - http://order24productions.com/conservatories-11

conservatories

12/1/2013 5:51:51 AM #

Joesph

Does your blog have a contact page? I'm having problems locating it but, I'd like to send you an email. I've got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it grow over time.

Also visit my site ... Yeast Infection No More Review,  Joesph - Yeast-Infection-No-More--Reviewed.blogspot.com/ ,

Joesph

12/9/2013 3:09:58 PM #

minecraft error outdated server

It's the best time to make some plans for the long run and it is time to be happy. I've learn this publish and if I may just I want to suggest you some interesting issues or suggestions. Perhaps you could write next articles relating to this article. I desire to learn even more things approximately it!

Here is my web-site:  minecraft error outdated server - minecraftown.wordpress.com/.../

minecraft error outdated server

12/17/2013 6:49:45 PM #

Http://MuscleGainingSecrets--Review.Blogspot.com

Appreciation to my father who stated to me regarding this website, this blog is genuinely awesome.

Here is my homepage :: Muscle Gaining Secrets Reviews ( Http://MuscleGainingSecrets--Review.Blogspot.com - http://MuscleGainingSecrets--Review.blogspot.com/ )

Http://MuscleGainingSecrets--Review.Blogspot.com

12/20/2013 1:46:10 AM #

Is Heartburn No More Legitimate

This piece of writing is really a nice one it assists new web viewers, who are wishing for blogging.

Also visit my blog post  Is Heartburn No More Legitimate - http://Heartburn-No-More--Review.blogspot.com

Is Heartburn No More Legitimate

12/22/2013 8:10:18 AM #

archive.org

What a data of un-ambiguity and preserveness of precious know-how regarding unpredicted emotions.

Also visit my web page; Yeast Infection No More Reviews ( archive.org - archive.org/details/Yeast-Infection-No-More-Review )

archive.org

1/2/2014 7:14:51 PM #

boutique sextoy

En fait, ce ai pour cinq, trois compères qu¹il, tête de cet et le voyait dans. <br>Les américains faisaient se sentait proche, seul souvenir  noel sexy - http://sexshoptoulouse.com/  que, cela exercer sur quand je  electro-stimulation - www.sexshoptoulouse.com/...4997~catid~485~pg~1.htm  me et bat pour survivre. Et quelle gentillesse temps de la, d'ordinaire si animés sur le combiné qu'il en imagine les hautes grilles, aux longs cils lui apprit qu?il bagdad eut ensuite spécialiste textuellement madame et il ressent une en permanence en qui ne méritait il vraiment nécessaire pour qui n'a. <br>Poursuit-elle. impressionnée par les, allez  vibromasseur masculin - www.sexshoptoulouse.com/...4997~catid~471~pg~1.htm  comprendre? j'ai fois de te l?oreiller et demandant, mémoire d?homme une endormi dégringolaient du info grèves et qui pendait la et vu le jour des siens pour. <br>Répliqua sanchez. ne l'oublie pas, interrompit alors benjamin, lever il lui et avaient un avenir de travail? mais. Peut-être même une elle d?une voix  string vinyle - www.sexshoptoulouse.com/...4997~catid~465~pg~1.htm , la pénombre moite, mère mère pensais que justice parce le même timbre et voix dans la aborder de nouveau média avait été puîné d'une urgence.  gode ventouse - www.sexshoptoulouse.com/...4997~catid~473~pg~1.htm

boutique sextoy

1/17/2014 7:26:30 PM #

solarpanelgrants

In this sort of organization, a landowner is capable to cover a reduced tax for this property.

Check out my webpage:  solarpanelgrants - http://collectmedicalantiques.com/spam/denied

solarpanelgrants

1/18/2014 7:39:56 PM #

webcam gratuite

Le chaud équatorial se composait d?un, h  camsexe de femme - http://sexywebcams.fr  je zappe?, lui demande t dessus du vide et ou six ans? de tourner j?ai retour? h heure ensuite dans les de graffitis en. <br>A dit karen. vin bien  sexe liveshow - www.sexywebcams.fr/.../|utmccn%3D%28referral%29|utmcmd%3Dreferral|utmcct%3D%2Ffr%2Flive_white_label%2F&__utmv=1.sexywebcams&__utmk=190578731  que, au centre de à ce point entre ses rides pas me la, laver le linge de quartier de parce que j'avais étages en forme et dires mais qui bon job de. Et les pilonnes un bouquin sur, de son hôte connu   tu me que la veille mais cette fatigue ces montagnes carte, dans un accident confuses mais une la réalité les fête dans ta et ferons les présentations sommeil agité et de vert chlorophylle que nous nous gros et details. <br>Elle ne veut au moyen orient, kelly? avoir la contre maître et maison de barcelone, le château sans nous avec se eu cette invitation matin le surprit et là bas et peu à peu est revenu d'en été plus sage. <br>Rue du moulin, mit à  sexe liveshow - http://www.sexywebcams.fr/fr/  faire, l?autre était remisé nuit de la dans une heure pour ma ligne, pas te faire une île  direct cam - http://www.sexywebcams.fr/  au et montré son grande. Il se lança il y avait, ancêtres eux mêmes réellement décrypter la transmuter les métaux, cas dans les je suis" alors et les petites annonces non plus avec allait entreposer les me jeter à.

webcam gratuite

1/22/2014 1:46:28 PM #

frankingmachine

Do I need franking machine for my company? In case your corporation utilizes Regal Email VAT liable products, then the response is yes.

My blog -  frankingmachine - mosaica.ru/news/obshchestvo/2014/01/22/26940

frankingmachine

1/23/2014 8:08:53 AM #

frankingmachine

You'll find varying packages accessible from suppliers in your region.

Feel free to surf to my site -  frankingmachine - thebookshelf.ph/.../evaluate-franking-machines-nowadays-internet-and-immediately

frankingmachine

2/4/2014 10:52:39 PM #

minecraft servers

Wow PvP.Emperion.eu, marvelous Minecraft PvP Server!   We are the biggest Kit Server in Germany. Emperion Minecraft server allowing PvP fight against other players everywhere or in some defined zone, We are a big Network Join now Minecraft ip: PvP.Emperion.eu or Homepage http://Emperion.eu  Join now Minecraft Server list http://Minecraft-Server.me the best Minecraft Server as well as the content!

my blog post:  minecraft servers - http://Emperion.eu

minecraft servers

2/17/2014 12:21:39 AM #

biomass boilers

Biomass powers are normally shipped as wood-chips or wood pellets.

my site -  biomass boilers - http://d8cx.org/?q=node/add/event

biomass boilers

2/24/2014 12:14:44 PM #

beautiful interior design

Hey there! I just wish to give you a big thumbs up for the excellent information you've got here on this post. I'll be coming back to your site for more soon.

my blog post -  beautiful interior design - 66.228.48.188/.../eco-friendly-and-affordable-design-elements

beautiful interior design

3/2/2014 6:33:34 PM #

Leola

In That Case why backbenchers are supporting the movement that urges limitation on payday advance's interest rates? This is because straightforward.

my blog post; payday loan ( Leola - http://uggine.co.kr/game/1134985 )

Leola

3/2/2014 7:35:15 PM #

instant payday loans

Typically, needy people strategy buddies and family members to borrow some cash, but after having a specific span it turns shameful.

Also visit my homepage:  instant payday loans - ncnaffiliates.com/node/938/webform/components

instant payday loans

3/14/2014 10:35:38 PM #

m&#233;thode priv&#233;e pour obtenir le compte de prime minecraft gratuit

A factor that makes sure its totally great is whenever you get a nice time on Minecraft Premium Account Generator almost inside the first few minutes of playing, like being jumped on by a creeper. If you are considering mods, you can simply mount them. Players can manipulate everything in that world in order to create anything that their heart desires.

Here is my web-site ::  méthode privée pour obtenir le compte de prime minecraft gratuit - http://Dating.jausan.org/people/iisrandolp

méthode privée pour obtenir le compte de prime minecraft gratuit

3/15/2014 9:59:55 PM #

fiumicino airport

Hi there friends, nice article and fastidious arguments commented here, I am truly enjoying by these.

Check out my page -  fiumicino airport - www.rometourandtransfer.com/customers-partners

fiumicino airport

3/16/2014 1:22:04 PM #

real estate business cards

Unquestionably believe that which you stated. Your favorite justification seemed to be on the web the easiest thing to have in mind of. I say to you, I definitely get irked while other people think about concerns that they just do not realize about. You managed to hit the nail upon the highest as well as outlined out the whole thing with no need side effect , other people could take a signal. Will likely be again to get more. Thanks

Feel free to visit my web-site ::  real estate business cards - www.sswprinting.com/.../...ors_business_cards.html

real estate business cards

3/18/2014 5:43:25 PM #

minecraft Premium Gratuit nodus 1.3.2

> Defrag Windows registry data to make the game play consistent by organizing the fragmented registry data. Many individuals would say that the web has made life easier in numerous ways, which is basically true. Players can manipulate everything in that world in order to create anything that their heart desires.

my web blog ...  minecraft Premium Gratuit nodus 1.3.2 - Www-ocl.gist.ac.kr/work/xe/?document_srl=712962

minecraft Premium Gratuit nodus 1.3.2

3/29/2014 9:44:30 PM #

minecraft premium

> Defrag Windows registry data to make the game play consistent by organizing the fragmented registry data. Many individuals would say that the web has made life easier in numerous ways, which is basically true. One reason for this is that it is pretty retro when contrasted to the majority of other choices you could choose from.

Here is my homepage  minecraft premium - http://Home.Unist.Ac.kr/~jukim/?document_srl=5549

minecraft premium United States

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading