Managing errors with exceptions PDF Print E-mail
User Rating: / 1
PoorBest 
Written by Paolo Brandoli   

It looks like I'm obsessed with error management and exceptions.

Well, having dealed with both applications that use the "old style" error code and the ones that uses exceptions, I've learned to appreciate the seconds, when well done.

Weird stuff

Nobody likes to deal with errors: they break the natural flow of your source code, they can crash your application, and your customers notice them before you do.

But the DO happen, so we better deal with them.

Until the exceptions were introduced, a classic way to deal with errors was to check for the return value of the called methods, or to call some kind of "GetLastError" function once in a while.

Legacy rulz

Some programmers love to deal with functions that return an error code, and they loves to call GetLastError() once in a while, usually because they can avoid to check for error codes and call GetLastError() at all. When they use exceptions they are forced to insert a lot of catch(...) statements to catch and ignore exceptions.

Some of them don't love error codes and GetLastError() kind of stuff but they hate exceptions, so they stick with the old school method.

Exceptions rulz

Exceptions are cool, when something goes wrong you just have to throw an exception. No more checking for error codes, no more uncool calls to GetLastError(), no more interferences with the natural flow of the code: all the "if(error) then do this otherwise do that" can disappear and we can finally appreciate a straightforward sequence of operations.

Or not?

Well, to start appreciating the exceptions you have to learn to live with them:

  • everything you allocate must be able to deallocate itself automatically. Easy with garbage collectors, easy also in C++ if you know how to do it (start looking for auto_ptr in the standard library, or shared_ptr in boost).
  • now exceptions are part of your application and your design should consider them too: you should plan their hierarchy and their behaviour

For instance, if your code allocates an handle, you must be sure that the handle will be released when it isn't needed anymore; you should write a class that takes care of that handle and releases it in the destructor.
A classical example are the Device Context Objects in Windows (pens, fonts, and so on): if you forget to release some of them you end up with an application that will be unusable few minutes after it has been launched.

Writing code that releases automatically the handles and resources is good also if you don't plan to use exceptions: multiple return point can be used without worries (yes, I like multile return points too), and in general you end up with much less memory and handles leaks.

Somebody said that exceptions are slow...

...and they prefer C to C++ because they say it is more efficient.

Not everything that is new is also slow: if you made the step from C to C++, then you can make one more step and start using exceptions. I've seen exceptions in a wide range of applications, and they NEVER were the cause for poor performances: if your application run slower, usually the last place you have to look for are the exceptions handlers.

Let's fart

Exceptions are like noisy farts: you notice them immediately, and most of the time you can tell who thrown it. If you forget to handle an exception, it will crash your application. Period.

Error codes and GetLastError() are like a silent fart: you can ignore it and everything seems normal until is too late to do something about it. And it is difficult to find the perpetrator.

This is just another reason to switch to exceptions: I prefer an honest noisy fart, I prefer the guy that raises its hand and says "Sorry, it was me", and then everybody laugh.

You will learn to love it when your application will just crash in front of you instead of giving you a wonderful, nicely formatted, shiny result, completly wrong, because of one GetLastError you forgot to call for the 1000th time.




Bookmark this
Digg!Reddit!Del.icio.us!Facebook!Slashdot!
 
< Prev   Next >

Search

  • 58a wycombe rd neutral bay
  • boxer seizures
  • air ferns
  • difference between an np and md
  • 1950 pro
  • evisu puma shoes
  • heart rate monitor strapless
  • advance wars music
  • middlesbrough churches
  • ceramic tile american olean counter rail
  • garden tractor leaf bagger
  • bianchi cases
  • ben cousins west coast
  • ala accredited colleges
  • free list top pro wrestlers
  • tectonic event
  • grace community church latham
  • birds of prey foundations
  • earths place in the galaxy
  • mecca hospital
  • breakpoint terrorists vs transhumanists by
  • 10 most haunted places in california
  • vaidance.com
  • 95-99 dodge neon lowering kits
  • fitz and floyd nutcracker centerpiece
  • dolce anad gabbana
  • abca started border collie for sale
  • 51 watchtower portishead
  • binnis locksmith
  • cairo banking company
  • atrium at treetops landover maryland
  • iud abortion of fertalized egg
  • bouncy inflatable castle georgetown tx
  • bear fur coats
  • australian summer solstice pagan celebration rite
  • cold heading
  • proven language systems
  • linwood harris
  • dakota lakota journal
  • 85 stated purchase super jumbo
  • 55b mac valve
  • aviator joystick
  • flour masa harina
  • homemade paint removers
  • alert bombings subscribe wireless
  • australia lab with leo laporte
  • homes sold east islip ny
  • dotflowers.com
  • geo metro refrigerant capacity
  • congressional investigation on enron
  • 2008 flstf fat boy
  • e thirteen bash guards
  • amaroso double jogger
  • alaska pfd estimates 2007
  • fotocommunity.de
  • contemporary musicals
  • bergen county animal shelter teterboro
  • chris mott
  • cindy paulson
  • 1st responder equipment in metairie area
  • hope likes reply mail inbox
  • ibn khaldun group feeling
  • 1 4 phono jack gold
  • brill 38 refurbished
  • cheri caffaro clips
  • newpapers in san antonio tx
  • lumix didital panasonic
  • 1860 s era acoustic guitars
  • city of passaic animal control
  • co-opliving.com
  • body works bloomingdale il
  • maine newpapers
  • car crashes involving acohol
  • burasari resort phuket
  • balboa flow switch problem
  • affairs of the heart and chord
  • 12 volt power supply
  • 1973 honda750 side cover emblems
  • 303 814 3183 harvest moon publishing
  • antique liquor cabnets
  • 1149 restaurant
  • air purifier rainbow
  • charles pellish pottsville
  • download jaspers warp
  • chrystal redekopp
  • american base okinawa
  • 101.5 wpdh home
  • 2008-2009 palm beach county school calendar
  • 2006 sti ings 1
  • texasteenage.org
  • fabian mata photo
  • antiqueguns.biz
  • avalon organics coq10 wrinkle defense creme
  • definition of scoliosis
  • strawberry-recipes.com
  • adam german shepherd colorado
  • bob bradshaw midi pedalboard
  • cheapest homeopathic hcg
  • chasingbooty.com
  • email archiving policies for
  • 176 f supp 159 dri 1959
  • d2 expansion cd keys
  • engineering hammers uk
  • aubrey millard
  • black grout for mosiac
  • ally mcbeal dancing baby free screensaver
  • bocce ball court coverings
  • childhood pyschology mythological figures tooth fairy
  • norweigian translating websites
  • 1982 camaro radiator upper fan shroud
  • o rappa reza vela
  • cheap-phentarmine.com
  • is rna a polynucleotide
  • english to italian translate
  • garnet collinson assult
  • findhotels.cc
  • aqua skipper video
  • 2008 ranking of colleges and universities
  • mickey thompson tres
  • grafted tropical hibiscus hybrids
  • grease equivalents chart
  • is mortgage insurance premiums tax deductible
  • dog obedience books
  • cheap car petrol in singapore
  • acrylic counter display
  • big bay point lighthouse
  • 146.610 red cross net
  • cheap rey mysterio mask
  • personl-loans.net
  • america bass bays macon al cemetery
  • crc cutting oil
  • yeti crab
  • gmisurveys.com
  • australia mildred hahn
  • automotive frame benches
  • disorders of the male reproductive system
  • agence immobili re li ge maastricht
  • bp brasil cnpj
  • ac milan tennis arsenal
  • audrina partridge divine rights of deni
  • harman becker top employer
  • och dmeiglechkeet mat der online
  • how to become a ufo researcher
  • bigtitsarea.com
  • georgia national fairground
  • 1988 oldsmobile cutlass supreme for sale
  • button zipper extender waist extender
  • 1998 santa barbara 93401
  • build mirror grinding machine
  • current fha rates in illinois
  • 26592 net other say
  • 5 8 radius hinge marker
  • brittany commando
  • berwick upon tweed
  • bill callahan nebraska
  • a-bis interface
  • conklin filters
  • amazon bookstore online
  • copper chimney cover single flue
  • big tomato neenah wi
  • bear clan lakota
  • linwood pa bed and breakfast
  • millerauditorium.com
  • limp bizkit futuristic video
  • home care technology magazine subscribe
  • 1973 elton john hit and brother
  • 1502 martin salina
  • 84 tall bookcases
  • amco server racks
  • vetscite.org
  • coller and leash slave
  • paddle pushbar for storefront door
  • history of walgreens
  • 0 gauge amplifier power wires
  • $100 coupon from iphone
  • tjc.com
  • aries leo astrology
  • auto for sale bmw m3
  • j kevin kindred
  • beachcomber 580 jacuzzi
  • bird mite cage
  • acord inc wallingford ct
  • belaire chinese restaurant hurst texas
  • online-slots.tv
  • definicion de estado
  • chauffer driven cars
  • mumbai terrorists mauritius
  • michele wynne
  • alchohol effects on humans
  • kimberly kimble indiana
  • columbian exposition memorabilia
  • gorillas
  • .311 pistol bullets
  • 1998 mb sport b52 for sale
  • all okinawa kobudo association
  • fabian brunnstrom
  • missouri synod luthern church
  • brentwood bay retail
  • alias hotel seattle brighton
  • bass guitar chord book
  • har levert til underskelsen vil
  • morethenasian.com
  • 1880 naples italy industry
  • large villa rental lucca
  • 1999 richmond oilers basketball roster
  • builderssurplus.net
  • 1858 father and brother lap desk
  • banquet checklist
  • cinemark movie theater in paducah
  • ejcareer.com
  • adrienne rolla
  • for love or money gymnastic meet
  • about print publishing
  • access to care pharmacy muncie in
  • christine tomlinson
  • accuguide ruler
  • arguments for and against labour unions
  • epi genetics definiiton
  • pontiac grandville dual exhaust system
  • bimini boat tops for sale
  • balboa board oh
  • leonard contreras sandoval oregon arizona
  • alarms home temperature moisture
  • getting married in lv
  • abide with me elizabeth stout
  • airport shuttle from prescott to phx
  • affect of pineapple juice on arthritis
  • alaska state real estate complaints
  • a poem about sodium
  • artist featured on shaw fundraiser
  • alfonso ruiz soto
  • definicion de cartools bancarias
  • cash carry kirkland wa
  • internethotels.com
  • 3 4 wooden tiles
  • abscess on the femoral artery symptoms
  • onlinelittlerock.com
  • 2002 bmw 745i complaints
  • 1997 honda cr-v timing marks
  • bridgeport vertical milling machine 1 2j
  • ebonydate.com
  • battery mah rating
  • big block olds engine builds
  • auto paint removers
  • chapin 2209
  • bus from chiang mai to phuket
  • arkansas lap band
  • beat pro strapless
  • attention case caught forward thought
  • english-spanish translater
  • ethan allen clock
  • texaco controlled combustion cycle
  • don guerra los banos
  • annapolis royal sun set ceremony 2007
  • eternal flame wny
  • assemble meal parties
  • yuntobulator.com
  • catawba falls preserve
  • microscopic colotis
  • santander central hispano bank services
  • rentvacations.com
  • efer endoscopy
  • angels for hire lubbock
  • shokos.com
  • cucumbers heathy
  • animal shelter in kissimmee
  • 2 inch poly pipe cost
  • cider vinegar uterine prolapse
  • elna jubilee sewing machine
  • 1962 johnny mathis hit
  • barracuda snorkel
  • 2003 rockwood premier 1904
  • 12v pir alarm system
  • hand sanitizer toxins
  • cpm programs
  • 20 minute winsor pilates torrent
  • ashmatic kitty
  • fibreglass pedal cars
  • kimberly ritter in tortola
  • about shel silverstein
  • australian knitting mills products
  • corned beef on new years
  • arms of a woman backing track
  • elk county topography pa
  • define industry norms
  • 2009 personal essay and memoir submissions
  • broiler litter moisture content determination
  • lease versus purchase memorandum
  • 2005 max lite 21rs
  • jem guitars forsale
  • b2v borrelli-vo salon britney spears
  • decoding a jeep cherokee vin
  • paraguay texaco
  • benjamin w latham
  • christian inspirational poems and quotes
  • stuckiniowa.com
  • ethylene glycol freezing point depression
  • 1980-1985 la lakers
  • 2002 british open champ el
  • amar singh
  • adventist medical center okinawa
  • 1994 camry timing belt
  • crispy new freestyle
  • john littlefinger lakota
  • adam schneider
  • collies breeding
  • articles for newsletters
  • castle near dresden lodging
  • 180 kph to mph
  • alarm clock hey baby wake up
  • 26760 hickory loop lutz florida
  • 86mm graduated neutral density
  • a debate about clone
  • cat relatives
  • a bibliography of color and philosophy
  • gaurav chopra
  • antiobiotic for staph
  • racism still exists today
  • apb hungarian police
  • baba jaspal singh
  • a healthy womb
  • chevy remanufactured transmissions
  • 17th century renaissance clothing dress life
  • kdirectory.co.uk
  • ak-74 tantal rifle grip
  • barring any delays
  • austraion opel
  • archival paper