<?xml version="1.0" encoding="windows-1252"?>
<node id="230799" title="Best Practices for Exception Handling" created="2003-01-28 18:04:05" updated="2005-08-13 07:50:24">
<type id="115">
perlquestion</type>
<author id="17000">
Ovid</author>
<data>
<field name="doctext">
&lt;p&gt;I didn't program Java for very long, so I really never quite understood the best way to handle exceptions.  (The one thing that I miss  in Perl is compile-time checking of whether or not the exceptions are caught, but that's a side issue).  Recently, I was struggling to get an API just write (sic) and the simplest way to do it seemed to be the following:&lt;/p&gt;

&lt;code&gt;
my $data = $self-&gt;__validate_added_data;
if ( UNIVERSAL::isa( $data, 'Foo::Form' ) ) {
    # add the data
}
else {
    # process the error
}
&lt;/code&gt;

&lt;p&gt;In other words, if I get back a valid Form object, I can add the data to the database.  Otherwise, I have a hashref that contains the form error information.  This error information is user error -- not program error.  As a result, I don't want to die or warn, yet variants of those are typical Perl error handling mechanisms.  Further, I have a method that returns two fundamentally different types of data:  and object or a hashref.  I finally started using the [cpan://Error] module and now use try/catch blocks to handle the types of errors that I need.&lt;/p&gt;

&lt;code&gt;
try {
    my $data = $self-&gt;__validate_added_data;
    # add the data
}
catch FormValidationError with {
    # process the error
};
&lt;/code&gt;

&lt;p&gt;Combining this with [cpan://Test::Exception] has made my tests simpler and my code more self-documenting.  However, I'm not entirely sure what are "best practices" for exception handling in this manner.  Can anyone offer their wisdom?&lt;/p&gt;

&lt;p&gt;Cheers,&lt;br /&gt;
&lt;a href="/index.pl?node=Ovid&amp;lastnode_id=1072"&gt;Ovid&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;small&gt;New address of &lt;a href="http://users.easystreet.com/ovid/cgi_course/"&gt;my CGI Course&lt;/a&gt;.&lt;br /&gt;
[http://users.easystreet.com/ovid/philosophy/decency.txt|Silence is Evil] (feel free to copy and distribute widely - note copyright text)&lt;/small&gt;&lt;/p&gt;</field>
</data>
</node>
