Exception Handling (when to use it)

Ovid publiustemp-londonpm at yahoo.com
Fri Jul 13 08:31:34 BST 2007

----- Original Message ----
From: David Cantrell <david at cantrell.org.uk>

> With that in mind, what do you think of my practice in Number::Phone et
> al of returning 1 to mean "yes" (eg yes, this is a mobile number), 0 to
> mean "no" (no, it's not a mobile number) and undef for "dunno"?

A good rule of thumb to distinguish between an exception or a boolean is the following:  

    Assuming everything in your software ran perfectly, the software's
    behavior should be unchanged if all exception handling is removed.

In your example, that's exactly the sort of time that a boolean response is fine and the code would be seriously crippled if $number->is_mobile threw an exception.  Your code is fine.

A perfect counter-example comes from a very clueless Java professor.  He was a bit confused by the jUnit tests I turned in with a project and in discussing them, I mentioned that I couldn't figure out how to get the tests to click a "Close" button in the Swing framework when I ran out of database records to read.

The instructor said "Oh, that's easy.  When you have no more records to read in a table, you want to throw an exception and your tests will catch it".

Wrong, wrong, wrong, wrong, wrong.  


Double f***ing wrong!

Running out of records in a table is a normal condition.  If I did what he said and later removed exception handling, the program would have ceased to function because normal conditions weren't accounted for.

(Dumbass instructor)

Side note:  some Java programmers who understand exceptions may still be leery about using them for things that Perl programmers wouldn't because in Java, exceptions can be very expensive to throw and catch (the reasons were explained in detail to me once, but I was too stupid to remember it).  Keep that in mind if you ask Java programmers about exceptions.

Buy the book  - http://www.oreilly.com/catalog/perlhks/
Perl and CGI  - http://users.easystreet.com/ovid/cgi_course/
Personal blog - http://publius-ovidius.livejournal.com/
Tech blog     - http://use.perl.org/~Ovid/journal/

More information about the london.pm mailing list