<?xml version="1.0" encoding="windows-1252"?>
<node id="230921" title="Re^2: Best Practices for Exception Handling" created="2003-01-29 06:47:32" updated="2005-07-27 17:28:53">
<type id="11">
note</type>
<author id="186362">
adrianh</author>
<data>
<field name="doctext">
&lt;p&gt;I'd add another vote for [cpan://Exception::Class]. It allows exceptions classes to be declared quickly and easily and has become my fave since discovering its existance.&lt;/p&gt;

&lt;p&gt;I tend to have a single module that declares all my exceptions. So for my Foo application I'd have something like:&lt;/p&gt;

&lt;code&gt;
package Foo::Exceptions;
use strict;
use warnings;

use Exception::Class (

	'Foo::Exception::DBI' =&gt; {
		description =&gt; 'DBI Error',
		# error =&gt; $DBI::errstr,
	},

	'Foo::Exception::DBI::Dupe' =&gt; {
		description =&gt; 'Duplicate key',
		isa =&gt; 'Foo::Exception::DBI',
		# error =&gt; name of duplicate key,
	},
	
	'Foo::Exception::Dupe' =&gt; {
		description =&gt; 'Duplicate entry',
		fields =&gt; [ 'name' ],
		# error =&gt; value of duplicate field
	},

        # etc.

);
&lt;/code&gt;

&lt;p&gt;Comments are because [cpan://Exception::Class] objects have a default "error" field and I like to document what that should be used for where I declare the class.&lt;/p&gt;


&lt;p&gt;Throw exceptions like this:&lt;/p&gt;

&lt;code&gt;
Foo::Exception::DBI-&gt;throw($DBI::errstr)
Foo::Exception::Dupe-&gt;throw(name =&gt; $name, error =&gt; $value);
&lt;/code&gt;

&lt;p&gt;Because of the closure issues [id://230804|raised by thraxil], I use the &lt;code&gt;eval / if &lt;/code&gt; idiom instead of any of the modules that provide extra try/catch syntax.&lt;/p&gt;

&lt;code&gt;
eval {$foo-&gt;something_that_might_die};
if (ref($@)) {
    if ($@-&gt;isa('Foo::Exception::Dupe') ) {
        warn "duplicate entry ", $@-&gt;name, " ($@)\n"; undef $@;
    };
};
die $@ if $@;
&lt;/code&gt;
</field>
<field name="root_node">
230799</field>
<field name="parent_node">
230807</field>
</data>
</node>
