1Exception::Base(3)    User Contributed Perl Documentation   Exception::Base(3)
2
3
4

NAME

6       Exception::Base - Lightweight exceptions
7

SYNOPSIS

9         # Use module and create needed exceptions
10         use Exception::Base
11            'Exception::Runtime',              # create new module
12            'Exception::System',               # load existing module
13            'Exception::IO',          => {
14                isa => 'Exception::System' },  # create new based on existing
15            'Exception::FileNotFound' => {
16                isa => 'Exception::IO',        # create new based on previous
17                message => 'File not found',   # override default message
18                has => [ 'filename' ],         # define new rw attribute
19                string_attributes => [ 'message', 'filename' ],
20            };                                 # output message and filename
21
22         # eval is used as "try" block
23         eval {
24           open my $file, '/etc/passwd'
25             or Exception::FileNotFound->throw(
26                   message=>'Something wrong',
27                   filename=>'/etc/passwd');
28         };
29         # syntax for Perl >= 5.10
30         use feature 'switch';
31         if ($@) {
32           given (my $e = Exception::Base->catch) {
33             when ($e->isa('Exception::IO')) { warn "IO problem"; }
34             when ($e->isa('Exception::Eval')) { warn "eval died"; }
35             when ($e->isa('Exception::Runtime')) { warn "some runtime was caught"; }
36             when ($e->matches({value=>9})) { warn "something happened"; }
37             when ($e->matches(qr/^Error/)) { warn "some error based on regex"; }
38             default { $e->throw; } # rethrow the exception
39           }
40         }
41         # standard syntax for older Perl
42         if ($@) {
43           my $e = Exception::Base->catch;   # convert $@ into exception
44           if ($e->isa('Exception::IO')) { warn "IO problem"; }
45           elsif ($e->isa('Exception::Eval')) { warn "eval died"; }
46           elsif ($e->isa('Exception::Runtime')) { warn "some runtime was caught"; }
47           elsif ($e->matches({value=>9})) { warn "something happened"; }
48           elsif ($e->matches(qr/^Error/)) { warn "some error based on regex"; }
49           else { $e->throw; } # rethrow the exception
50         }
51
52         # $@ has to be recovered ASAP!
53         eval { die "this die will be caught" };
54         my $e = Exception::Base->catch;
55         eval { die "this die will be ignored" };
56         if ($e) {
57            (...)
58         }
59
60         # the exception can be thrown later
61         my $e = Exception::Base->new;
62         # (...)
63         $e->throw;
64
65         # ignore our package in stack trace
66         package My::Package;
67         use Exception::Base '+ignore_package' => __PACKAGE__;
68
69         # define new exception in separate module
70         package Exception::My;
71         use Exception::Base (__PACKAGE__) => {
72             has => ['myattr'],
73         };
74
75         # run Perl with changed verbosity for debugging purposes
76         $ perl -MException::Base=verbosity,4 script.pl
77

DESCRIPTION

79       This class implements a fully OO exception mechanism similar to
80       Exception::Class or Class::Throwable.  It provides a simple interface
81       allowing programmers to declare exception classes.  These classes can
82       be thrown and caught.  Each uncaught exception prints full stack trace
83       if the default verbosity is increased for debugging purposes.
84
85       The features of "Exception::Base":
86
87       · fast implementation of the exception class
88
89       · fully OO without closures and source code filtering
90
91       · does not mess with $SIG{__DIE__} and $SIG{__WARN__}
92
93       · no external run-time modules dependencies, requires core Perl modules
94         only
95
96       · the default behavior of exception class can be changed globally or
97         just for the thrown exception
98
99       · matching the exception by class, message or other attributes
100
101       · matching with string, regex or closure function
102
103       · creating automatically the derived exception classes ("use" in
104         perlfunc interface)
105
106       · easily expendable, see Exception::System class for example
107
108       · prints just an error message or dumps full stack trace
109
110       · can propagate (rethrow) an exception
111
112       · can ignore some packages for stack trace output
113
114       · some defaults (i.e. verbosity) can be different for different
115         exceptions
116

OVERLOADS

118       Boolean context
119           True value.  See "to_bool" method.
120
121             eval { Exception::Base->throw( message=>"Message", value=>123 ) };
122             if ($@) {
123                # the exception object is always true
124             }
125
126       Numeric context
127           Content of attribute pointed by "numeric_attribute" attribute.  See
128           "to_number" method.
129
130             eval { Exception::Base->throw( message=>"Message", value=>123 ) };
131             print 0+$@;           # 123
132
133       String context
134           Content of attribute which is combined from "string_attributes"
135           attributes with additional information, depended on "verbosity"
136           setting.  See "to_string" method.
137
138             eval { Exception::Base->throw( message=>"Message", value=>123 ) };
139             print "$@";           # "Message at -e line 1.\n"
140
141       "~~"
142           Smart matching operator.  See "matches" method.
143
144             eval { Exception::Base->throw( message=>"Message", value=>123 ) };
145             print "Message" ~~ $@;                          # 1
146             print qr/message/i ~~ $@;                       # 1
147             print ['Exception::Base'] ~~ $@;                # 1
148             print 123 ~~ $@;                                # 1
149             print {message=>"Message", value=>123} ~~ $@;   # 1
150
151           Warning: The smart operator requires that the exception object is a
152           second argument.
153

CONSTANTS

155       ATTRS
156           Declaration of class attributes as reference to hash.
157
158           The attributes are listed as name => {properties}, where properties
159           is a list of attribute properties:
160
161           is  Can be 'rw' for read-write attributes or 'ro' for read-only
162               attributes.  The attribute is read-only and does not have an
163               accessor created if 'is' property is missed.
164
165           default
166               Optional property with the default value if the attribute value
167               is not defined.
168
169           The read-write attributes can be set with "new" constructor.  Read-
170           only attributes and unknown attributes are ignored.
171
172           The constant have to be defined in derived class if it brings
173           additional attributes.
174
175             package Exception::My;
176             use base 'Exception::Base';
177
178             # Define new class attributes
179             use constant ATTRS => {
180               %{Exception::Base->ATTRS},       # base's attributes have to be first
181               readonly  => { is=>'ro' },                   # new ro attribute
182               readwrite => { is=>'rw', default=>'blah' },  # new rw attribute
183             };
184
185             package main;
186             use Exception::Base ':all';
187             eval {
188               Exception::My->throw( readwrite => 2 );
189             };
190             if ($@) {
191               my $e = Exception::Base->catch;
192               print $e->readwrite;                # = 2
193               print $e->defaults->{readwrite};    # = "blah"
194             }
195

ATTRIBUTES

197       Class attributes are implemented as values of blessed hash.  The
198       attributes are also available as accessors methods.
199
200       message (rw, default: 'Unknown exception')
201           Contains the message of the exception.  It is the part of the
202           string representing the exception object.
203
204             eval { Exception::Base->throw( message=>"Message" ); };
205             print $@->message if $@;
206
207           It can also be an array reference of strings and then the
208           "perlfunc" in sprintf is used to get a message.
209
210             Exception::Base->throw( message => ["%s failed", __PACKAGE__] );
211
212       value (rw, default: 0)
213           Contains the value which represents numeric value of the exception
214           object in numeric context.
215
216             eval { Exception::Base->throw( value=>2 ); };
217             print "Error 2" if $@ == 2;
218
219       verbosity (rw, default: 2)
220           Contains the verbosity level of the exception object.  It allows to
221           change the string representing the exception object.  There are
222           following levels of verbosity:
223
224           0 Empty string
225
226           1
227              Message
228
229           2
230              Message at %s line %d.
231
232             The same as the standard output of die() function.  It doesn't
233             include "at %s line %d." string if message ends with "\n"
234             character.  This is the default option.
235
236           3
237              Class: Message at %s line %d
238                      %c_ = %s::%s() called in package %s at %s line %d
239                      ...propagated in package %s at %s line %d.
240              ...
241
242             The output contains full trace of error stack without first
243             "ignore_level" lines and those packages which are listed in
244             "ignore_package" and "ignore_class" settings.
245
246           4 The output contains full trace of error stack.  In this case the
247             "ignore_level", "ignore_package" and "ignore_class" settings are
248             meaning only for first line of exception's message.
249
250           If the verbosity is undef, then the default verbosity for exception
251           objects is used.
252
253           If the verbosity set with constructor ("new" or "throw") is lower
254           than 3, the full stack trace won't be collected.
255
256           If the verbosity is lower than 2, the full system data (time, pid,
257           tid, uid, euid, gid, egid) won't be collected.
258
259           This setting can be changed with import interface.
260
261             use Exception::Base verbosity => 4;
262
263           It can be also changed for Perl interpreter instance, i.e. for
264           debugging purposes.
265
266             sh$ perl -MException::Base=verbosity,4 script.pl
267
268       ignore_package (rw)
269           Contains the name (scalar or regexp) or names (as references array)
270           of packages which are ignored in error stack trace.  It is useful
271           if some package throws an exception but this module shouldn't be
272           listed in stack trace.
273
274             package My::Package;
275             use Exception::Base;
276             sub my_function {
277               do_something() or throw Exception::Base ignore_package=>__PACKAGE__;
278               throw Exception::Base ignore_package => [ "My", qr/^My::Modules::/ ];
279             }
280
281           This setting can be changed with import interface.
282
283             use Exception::Base ignore_package => __PACKAGE__;
284
285       ignore_class (rw)
286           Contains the name (scalar) or names (as references array) of
287           packages which are base classes for ignored packages in error stack
288           trace.  It means that some packages will be ignored even the
289           derived class was called.
290
291             package My::Package;
292             use Exception::Base;
293             Exception::Base->throw( ignore_class => "My::Base" );
294
295           This setting can be changed with import interface.
296
297             use Exception::Base ignore_class => "My::Base";
298
299       ignore_level (rw)
300           Contains the number of level on stack trace to ignore.  It is
301           useful if some package throws an exception but this module
302           shouldn't be listed in stack trace.  It can be used with or without
303           ignore_package attribute.
304
305             # Convert warning into exception. The signal handler ignores itself.
306             use Exception::Base 'Exception::My::Warning';
307             $SIG{__WARN__} = sub {
308               Exception::My::Warning->throw( message => $_[0], ignore_level => 1 );
309             };
310
311       time (ro)
312           Contains the timestamp of the thrown exception.  Collected if the
313           verbosity on throwing exception was greater than 1.
314
315             eval { Exception::Base->throw( message=>"Message" ); };
316             print scalar localtime $@->time;
317
318       pid (ro)
319           Contains the PID of the Perl process at time of thrown exception.
320           Collected if the verbosity on throwing exception was greater than
321           1.
322
323             eval { Exception::Base->throw( message=>"Message" ); };
324             kill 10, $@->pid;
325
326       tid (ro)
327           Contains the tid of the thread or undef if threads are not used.
328           Collected if the verbosity on throwing exception was greater than
329           1.
330
331       uid (ro)
332       euid (ro)
333       gid (ro)
334       egid (ro)
335           Contains the real and effective uid and gid of the Perl process at
336           time of thrown exception.  Collected if the verbosity on throwing
337           exception was greater than 1.
338
339       caller_stack (ro)
340           Contains the error stack as array of array with information about
341           caller functions.  The first 8 elements of the array's row are the
342           same as first 8 elements of the output of "caller" function.
343           Further elements are optional and are the arguments of called
344           function.  Collected if the verbosity on throwing exception was
345           greater than 1.  Contains only the first element of caller stack if
346           the verbosity was lower than 3.
347
348           If the arguments of called function are references and
349           "Scalar::Util::weaken" function is available then reference is
350           weakened.
351
352             eval { Exception::Base->throw( message=>"Message" ); };
353             ($package, $filename, $line, $subroutine, $hasargs, $wantarray,
354             $evaltext, $is_require, @args) = $@->caller_stack->[0];
355
356       propagated_stack (ro)
357           Contains the array of array which is used for generating
358           "...propagated at" message.  The elements of the array's row are
359           the same as first 3 elements of the output of "caller" function.
360
361       max_arg_len (rw, default: 64)
362           Contains the maximal length of argument for functions in backtrace
363           output.  Zero means no limit for length.
364
365             sub a { Exception::Base->throw( max_arg_len=>5 ) }
366             a("123456789");
367
368       max_arg_nums (rw, default: 8)
369           Contains the maximal number of arguments for functions in backtrace
370           output.  Zero means no limit for arguments.
371
372             sub a { Exception::Base->throw( max_arg_nums=>1 ) }
373             a(1,2,3);
374
375       max_eval_len (rw, default: 0)
376           Contains the maximal length of eval strings in backtrace output.
377           Zero means no limit for length.
378
379             eval "Exception->throw( max_eval_len=>10 )";
380             print "$@";
381
382       defaults
383           Meta-attribute contains the list of default values.
384
385             my $e = Exception::Base->new;
386             print defined $e->{verbosity}
387               ? $e->{verbosity}
388               : $e->{defaults}->{verbosity};
389
390       default_attribute (default: 'message')
391           Meta-attribute contains the name of the default attribute.  This
392           attribute will be set for one argument throw method.  This
393           attribute has meaning for derived classes.
394
395             use Exception::Base 'Exception::My' => {
396                 has => 'myattr',
397                 default_attribute => 'myattr',
398             };
399
400             eval { Exception::My->throw("string") };
401             print $@->myattr;    # "string"
402
403       numeric_attribute (default: 'value')
404           Meta-attribute contains the name of the attribute which contains
405           numeric value of exception object.  This attribute will be used for
406           representing exception in numeric context.
407
408             use Exception::Base 'Exception::My' => {
409                 has => 'myattr',
410                 numeric_attribute => 'myattr',
411             };
412
413             eval { Exception::My->throw(myattr=>123) };
414             print 0 + $@;    # 123
415
416       eval_attribute (default: 'message')
417           Meta-attribute contains the name of the attribute which is filled
418           if error stack is empty.  This attribute will contain value of $@
419           variable.  This attribute has meaning for derived classes.
420
421             use Exception::Base 'Exception::My' => {
422                 has => 'myattr',
423                 eval_attribute => 'myattr'
424             };
425
426             eval { die "string" };
427             print $@->myattr;    # "string"
428
429       string_attributes (default: ['message'])
430           Meta-attribute contains the array of names of attributes with
431           defined value which are joined to the string returned by
432           "to_string" method.  If none of attributes are defined, the string
433           is created from the first default value of attributes listed in the
434           opposite order.
435
436             use Exception::Base 'Exception::My' => {
437                 has => 'myattr',
438                 myattr => 'default',
439                 string_attributes => ['message', 'myattr'],
440             };
441
442             eval { Exception::My->throw( message=>"string", myattr=>"foo" ) };
443             print $@->myattr;    # "string: foo"
444
445             eval { Exception::My->throw() };
446             print $@->myattr;    # "default"
447

IMPORTS

449       "use Exception::Base 'attribute' =" value;>
450           Changes the default value for attribute.  If the attribute name has
451           no special prefix, its default value is replaced with a new value.
452
453             use Exception::Base verbosity => 4;
454
455           If the attribute name starts with ""+"" or ""-"" then the new value
456           is based on previous value:
457
458           ·   If the original value was a reference to array, the new value
459               can be included or removed from original array.  Use array
460               reference if you need to add or remove more than one element.
461
462                 use Exception::Base
463                     "+ignore_packages" => [ __PACKAGE__, qr/^Moose::/ ],
464                     "-ignore_class" => "My::Good::Class";
465
466           ·   If the original value was a number, it will be incremented or
467               decremented by the new value.
468
469                 use Exception::Base "+ignore_level" => 1;
470
471           ·   If the original value was a string, the new value will be
472               included.
473
474                 use Exception::Base "+message" => ": The incuded message";
475
476       "use Exception::Base 'Exception', ...;"
477           Loads additional exception class module.  If the module is not
478           available, creates the exception class automatically at compile
479           time.  The newly created class will be based on "Exception::Base"
480           class.
481
482             use Exception::Base qw{ Exception::Custom Exception::SomethingWrong };
483             Exception::Custom->throw;
484
485       "use Exception::Base 'Exception' =" { isa => BaseException, version =>
486       version, ... };>
487           Loads additional exception class module.  If the module's version
488           is lower than given parameter or the module can't be loaded,
489           creates the exception class automatically at compile time.  The
490           newly created class will be based on given class and has the given
491           $VERSION variable.
492
493           isa The newly created class will be based on given class.
494
495                 use Exception::Base
496                   'Exception::My',
497                   'Exception::Nested' => { isa => 'Exception::My };
498
499           version
500               The class will be created only if the module's version is lower
501               than given parameter and will have the version given in the
502               argument.
503
504                 use Exception::Base
505                   'Exception::My' => { version => 1.23 };
506
507           has The class will contain new rw attribute (if parameter is a
508               string) or new rw attributes (if parameter is a reference to
509               array of strings) or new rw or ro attributes (if parameter is a
510               reference to hash of array of strings with rw and ro as hash
511               key).
512
513                 use Exception::Base
514                   'Exception::Simple' => { has => 'field' },
515                   'Exception::More' => { has => [ 'field1', 'field2' ] },
516                   'Exception::Advanced' => { has => {
517                       ro => [ 'field1', 'field2' ],
518                       rw => [ 'field3' ]
519                   } };
520
521           message
522           verbosity
523           max_arg_len
524           max_arg_nums
525           max_eval_len
526           other attribute having default property
527               The class will have the default property for the given
528               attribute.
529
530             use Exception::Base
531               'Exception::WithDefault' => { message => 'Default message' },
532               'Exception::Reason' => {
533                   has => [ 'reason' ],
534                   string_attributes => [ 'message', 'reason' ] };
535

CONSTRUCTORS

537       new([%args])
538           Creates the exception object, which can be thrown later.  The
539           system data attributes like "time", "pid", "uid", "gid", "euid",
540           "egid" are not filled.
541
542           If the key of the argument is read-write attribute, this attribute
543           will be filled. Otherwise, the argument will be ignored.
544
545             $e = Exception::Base->new(
546                      message=>"Houston, we have a problem",
547                      unknown_attr => "BIG"
548                  );
549             print $e->{message};
550
551           The constructor reads the list of class attributes from ATTRS
552           constant function and stores it in the internal cache for
553           performance reason.  The defaults values for the class are also
554           stored in internal cache.
555
556       "CLASS"->throw([%args]])
557           Creates the exception object and immediately throws it with "die"
558           system function.
559
560             open my $fh, $file
561               or Exception::Base->throw( message=>"Can not open file: $file" );
562
563           The "throw" is also exported as a function.
564
565             open my $fh, $file
566               or throw 'Exception::Base' => message=>"Can not open file: $file";
567
568       The "throw" can be also used as a method.
569

METHODS

571       $obj->throw([%args])
572           Immediately throws exception object.  It can be used for rethrowing
573           existing exception object.  Additional arguments will override the
574           attributes in existing exception object.
575
576             $e = Exception::Base->new;
577             # (...)
578             $e->throw( message=>"thrown exception with overridden message" );
579
580             eval { Exception::Base->throw( message=>"Problem", value=>1 ) };
581             $@->throw if $@->value;
582
583       $obj->throw(message, [%args])
584           If the number of args list for arguments is odd, the first argument
585           is a message.  This message can be overridden by message from args
586           list.
587
588             Exception::Base->throw( "Problem", message=>"More important" );
589             eval { die "Bum!" };
590             Exception::Base->throw( $@, message=>"New message" );
591
592       CLASS->throw($exception, [%args])
593           Immediately rethrows an existing exception object as an other
594           exception class.
595
596             eval { open $f, "w", "/etc/passwd" or Exception::System->throw };
597             # convert Exception::System into Exception::Base
598             Exception::Base->throw($@);
599
600       CLASS->catch([$variable])
601           The exception is recovered from variable argument or $@ variable if
602           variable argument was empty.  Then also $@ is replaced with empty
603           string to avoid an endless loop.
604
605           The method returns an exception object if exception is caught or
606           undefined value otherwise.
607
608             eval { Exception::Base->throw; };
609             if ($@) {
610                 my $e = Exception::Base->catch;
611                 print $e->to_string;
612             }
613
614           If the value is not empty and does not contain the
615           "Exception::Base" object, new exception object is created with
616           class CLASS and its message is based on previous value with removed
617           " at file line 123." string and the last end of line (LF).
618
619             eval { die "Died\n"; };
620             my $e = Exception::Base->catch;
621             print ref $e;   # "Exception::Base"
622
623       matches(that)
624           Checks if the exception object matches the given argument.
625
626           The "matches" method overloads "~~" smart matching operator.
627           Warning: The second argument for smart matching operator needs to
628           be scalar.
629
630           If the argument is a reference to array, it is checked if the
631           object is a given class.
632
633             use Exception::Base
634               'Exception::Simple',
635               'Exception::Complex' => { isa => 'Exception::Simple };
636             eval { Exception::Complex->throw() };
637             print $@->matches( ['Exception::Base'] );                    # matches
638             print $@->matches( ['Exception::Simple', 'Exception::X'] );  # matches
639             print $@->matches( ['NullObject'] );                         # doesn't
640
641           If the argument is a reference to hash, attributes of the exception
642           object is matched.
643
644             eval { Exception::Base->throw( message=>"Message", value=>123 ) };
645             print $@->matches( { message=>"Message" } );             # matches
646             print $@->matches( { value=>123 } );                     # matches
647             print $@->matches( { message=>"Message", value=>45 } );  # doesn't
648
649           If the argument is a single string, regexp or code reference or is
650           undefined, the default attribute of the exception object is matched
651           (usually it is a "message" attribute).
652
653             eval { Exception::Base->throw( message=>"Message" ) };
654             print $@->matches( "Message" );                          # matches
655             print $@->matches( qr/Message/ );                        # matches
656             print $@->matches( qr/[0-9]/ );                          # doesn't
657             print $@->matches( sub{/Message/} );                     # matches
658             print $@->matches( sub{0} );                             # doesn't
659             print $@->matches( undef );                              # doesn't
660
661           If argument is a numeric value, the argument matches if "value"
662           attribute matches.
663
664             eval { Exception::Base->throw( value=>123, message=>456 ) } );
665             print $@->matches( 123 );                                # matches
666             print $@->matches( 456 );                                # doesn't
667
668           If an attribute contains array reference, the array will be
669           "sprintf"-ed before matching.
670
671             eval { Exception::Base->throw( message=>["%s", "Message"] ) };
672             print $@->matches( "Message" );                          # matches
673             print $@->matches( qr/Message/ );                        # matches
674             print $@->matches( qr/[0-9]/ );                          # doesn't
675
676           The "match" method matches for special keywords:
677
678           -isa
679               Matches if the object is a given class.
680
681                 eval { Exception::Base->new( message=>"Message" ) };
682                 print $@->matches( { -isa=>"Exception::Base" } );            # matches
683                 print $@->matches( { -isa=>["X::Y", "Exception::Base"] } );  # matches
684
685           -has
686               Matches if the object has a given attribute.
687
688                 eval { Exception::Base->new( message=>"Message" ) };
689                 print $@->matches( { -has=>"Message" } );                    # matches
690
691           -default
692               Matches against the default attribute, usually the "message"
693               attribute.
694
695                 eval { Exception::Base->new( message=>"Message" ) };
696                 print $@->matches( { -default=>"Message" } );                # matches
697
698       to_string
699           Returns the string representation of exception object.  It is
700           called automatically if the exception object is used in string
701           scalar context.  The method can be used explicitly.
702
703             eval { Exception::Base->throw; };
704             $@->{verbosity} = 1;
705             print "$@";
706             $@->verbosity = 4;
707             print $@->to_string;
708
709       to_number
710           Returns the numeric representation of exception object.  It is
711           called automatically if the exception object is used in numeric
712           scalar context.  The method can be used explicitly.
713
714             eval { Exception::Base->throw( value => 42 ); };
715             print 0+$@;           # 42
716             print $@->to_number;  # 42
717
718       to_bool
719           Returns the boolean representation of exception object.  It is
720           called automatically if the exception object is used in boolean
721           context.  The method can be used explicitly.
722
723             eval { Exception::Base->throw; };
724             print "ok" if $@;           # ok
725             print "ok" if $@->to_bool;  # ok
726
727       get_caller_stacktrace
728           Returns an array of strings or string with caller stack trace.  It
729           is implicitly used by "to_string" method.
730
731       PROPAGATE
732           Checks the caller stack and fills the "propagated_stack" attribute.
733           It is usually used if "die" system function was called without any
734           arguments.
735
736       _collect_system_data
737           Collects system data and fills the attributes of exception object.
738           This method is called automatically if exception if thrown or
739           created by "new" constructor.  It can be overridden by derived
740           class.
741
742             package Exception::Special;
743             use base 'Exception::Base';
744             use constant ATTRS => {
745               %{Exception::Base->ATTRS},
746               'special' => { is => 'ro' },
747             };
748             sub _collect_system_data {
749               my $self = shift;
750               $self->SUPER::_collect_system_data(@_);
751               $self->{special} = get_special_value();
752               return $self;
753             }
754             BEGIN {
755               __PACKAGE__->_make_accessors;
756             }
757             1;
758
759           Method returns the reference to the self object.
760
761       _make_accessors
762           Creates accessors for each attribute.  This static method should be
763           called in each derived class which defines new attributes.
764
765             package Exception::My;
766             # (...)
767             BEGIN {
768               __PACKAGE__->_make_accessors;
769             }
770
771       package
772           Returns the package name of the subroutine which thrown an
773           exception.
774
775       file
776           Returns the file name of the subroutine which thrown an exception.
777
778       line
779           Returns the line number for file of the subroutine which thrown an
780           exception.
781
782       subroutine
783           Returns the subroutine name which thrown an exception.
784

SEE ALSO

786       Repository: <http://github.com/dex4er/perl-Exception-Base>
787
788       There are more implementation of exception objects available on CPAN.
789       Please note that Perl has built-in implementation of pseudo-exceptions:
790
791         eval { die { message => "Pseudo-exception", package => __PACKAGE__,
792                      file => __FILE__, line => __LINE__ };
793         };
794         if ($@) {
795           print $@->{message}, " at ", $@->{file}, " in line ", $@->{line}, ".\n";
796         }
797
798       The more complex implementation of exception mechanism provides more
799       features.
800
801       Error
802           Complete implementation of try/catch/finally/otherwise mechanism.
803           Uses nested closures with a lot of syntactic sugar.  It is slightly
804           faster than "Exception::Base" module for failure scenario and is
805           much slower for success scenario.  It doesn't provide a simple way
806           to create user defined exceptions.  It doesn't collect system data
807           and stack trace on error.
808
809       Exception::Class
810           More Perlish way to do OO exceptions.  It is similar to
811           "Exception::Base" module and provides similar features but it is
812           10x slower for failure scenario.
813
814       Exception::Class::TryCatch
815           Additional try/catch mechanism for Exception::Class.  It is 15x
816           slower for success scenario.
817
818       Class::Throwable
819           Elegant OO exceptions similar to Exception::Class and
820           "Exception::Base".  It might be missing some features found in
821           "Exception::Base" and Exception::Class.
822
823       Exceptions
824           Not recommended.  Abandoned.  Modifies %SIG handlers.
825
826       TryCatch
827           A module which gives new try/catch keywords without source filter.
828
829       Try::Tiny
830           Smaller, simpler and slower version of TryCatch module.
831
832       The "Exception::Base" does not depend on other modules like
833       Exception::Class and it is more powerful than Class::Throwable.  Also
834       it does not use closures as Error and does not pollute namespace as
835       Exception::Class::TryCatch.  It is also much faster than
836       Exception::Class::TryCatch and Error for success scenario.
837
838       The "Exception::Base" is compatible with syntax sugar modules like
839       TryCatch and Try::Tiny.
840
841       The "Exception::Base" is also a base class for enhanced classes:
842
843       Exception::System
844           The exception class for system or library calls which modifies $!
845           variable.
846
847       Exception::Died
848           The exception class for eval blocks with simple "die" in perlfunc.
849           It can also handle $SIG{__DIE__} hook and convert simple "die" in
850           perlfunc into an exception object.
851
852       Exception::Warning
853           The exception class which handle $SIG{__WARN__} hook and convert
854           simple "warn" in perlfunc into an exception object.
855

EXAMPLES

857   New exception classes
858       The "Exception::Base" module allows to create new exception classes
859       easily.  You can use "import" in perlfunc interface or base module to
860       do it.
861
862       The "import" in perlfunc interface allows to create new class with new
863       read-write attributes.
864
865         package Exception::Simple;
866         use Exception::Base (__PACKAGE__) => {
867           has => qw{ reason method },
868           string_attributes => qw{ message reason method },
869         };
870
871       For more complex exceptions you can redefine "ATTRS" constant.
872
873         package Exception::Complex;
874         use base 'Exception::Base';
875         use constant ATTRS => {
876           %{ Exception::Base->ATTRS },     # SUPER::ATTRS
877           hostname => { is => 'ro' },
878           string_attributes => qw{ hostname message },
879         };
880         sub _collect_system_data {
881           my $self = shift;
882           my $hostname = `hostname`;
883           chomp $hostname;
884           $self->{hostname} = $hostname;
885           return $self->SUPER::_collect_system_data(@_);
886         }
887

PERFORMANCE

889       There are two scenarios for "eval" in perlfunc block: success or
890       failure.  Success scenario should have no penalty on speed.  Failure
891       scenario is usually more complex to handle and can be significantly
892       slower.
893
894       Any other code than simple "if ($@)" is really slow and shouldn't be
895       used if speed is important.  It means that any module which provides
896       try/catch syntax sugar should be avoided: Error,
897       Exception::Class::TryCatch, TryCatch, Try::Tiny.  Be careful because
898       simple "if ($@)" has many gotchas which are described in Try::Tiny's
899       documentation.
900
901       The "Exception::Base" module was benchmarked with other implementations
902       for simple try/catch scenario.  The results (Perl 5.10.1
903       x86_64-linux-thread-multi) are following:
904
905         -----------------------------------------------------------------------
906         | Module                              | Success sub/s | Failure sub/s |
907         -----------------------------------------------------------------------
908         | eval/die string                     |       3715708 |        408951 |
909         -----------------------------------------------------------------------
910         | eval/die object                     |       4563524 |        191664 |
911         -----------------------------------------------------------------------
912         | Exception::Base eval/if             |       4903857 |         11291 |
913         -----------------------------------------------------------------------
914         | Exception::Base eval/if verbosity=1 |       4790762 |         18833 |
915         -----------------------------------------------------------------------
916         | Error                               |        117475 |         26694 |
917         -----------------------------------------------------------------------
918         | Class::Throwable                    |       4618545 |         12678 |
919         -----------------------------------------------------------------------
920         | Exception::Class                    |        643901 |          3493 |
921         -----------------------------------------------------------------------
922         | Exception::Class::TryCatch          |        307825 |          3439 |
923         -----------------------------------------------------------------------
924         | TryCatch                            |        690784 |        294802 |
925         -----------------------------------------------------------------------
926         | Try::Tiny                           |        268780 |        158383 |
927         -----------------------------------------------------------------------
928
929       The "Exception::Base" module was written to be as fast as it is
930       possible.  It does not use internally i.e. accessor functions which are
931       slower about 6 times than standard variables.  It is slower than pure
932       die/eval for success scenario because it is uses OO mechanisms which
933       are slow in Perl.  It can be a little faster if some features are
934       disables, i.e. the stack trace and higher verbosity.
935
936       You can find the benchmark script in this package distribution.
937

BUGS

939       If you find the bug or want to implement new features, please report it
940       at <https://github.com/dex4er/perl-Exception-Base/issues>
941
942       The code repository is available at
943       <http://github.com/dex4er/perl-Exception-Base>
944

AUTHOR

946       Piotr Roszatycki <dexter@cpan.org>
947

LICENSE

949       Copyright (c) 2007-2015 Piotr Roszatycki <dexter@cpan.org>.
950
951       This program is free software; you can redistribute it and/or modify it
952       under the same terms as Perl itself.
953
954       See <http://dev.perl.org/licenses/artistic.html>
955
956
957
958perl v5.32.0                      2020-07-28                Exception::Base(3)
Impressum