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

NAME

6       Exception::Class - A module that allows you to declare real exception
7       classes in Perl
8

VERSION

10       version 1.44
11

SYNOPSIS

13         use Exception::Class (
14             'MyException',
15
16             'AnotherException' => { isa => 'MyException' },
17
18             'YetAnotherException' => {
19                 isa         => 'AnotherException',
20                 description => 'These exceptions are related to IPC'
21             },
22
23             'ExceptionWithFields' => {
24                 isa    => 'YetAnotherException',
25                 fields => [ 'grandiosity', 'quixotic' ],
26                 alias  => 'throw_fields',
27             },
28         );
29         use Scalar::Util qw( blessed );
30         use Try::Tiny;
31
32         try {
33             MyException->throw( error => 'I feel funny.' );
34         }
35         catch {
36             die $_ unless blessed $_ && $_->can('rethrow');
37
38             if ( $_->isa('Exception::Class') ) {
39                 warn $_->error, "\n", $_->trace->as_string, "\n";
40                 warn join ' ', $_->euid, $_->egid, $_->uid, $_->gid, $_->pid, $_->time;
41
42                 exit;
43             }
44             elsif ( $_->isa('ExceptionWithFields') ) {
45                 if ( $_->quixotic ) {
46                     handle_quixotic_exception();
47                 }
48                 else {
49                     handle_non_quixotic_exception();
50                 }
51             }
52             else {
53                 $_->rethrow;
54             }
55         };
56
57         # without Try::Tiny
58         eval { ... };
59         if ( my $e = Exception::Class->caught ) { ... }
60
61         # use an alias - without parens subroutine name is checked at
62         # compile time
63         throw_fields error => "No strawberry", grandiosity => "quite a bit";
64

DESCRIPTION

66       RECOMMENDATION 1: If you are writing modern Perl code with Moose or Moo
67       I highly recommend using Throwable instead of this module.
68
69       RECOMMENDATION 2: Whether or not you use Throwable, you should use
70       Try::Tiny.
71
72       Exception::Class allows you to declare exception hierarchies in your
73       modules in a "Java-esque" manner.
74
75       It features a simple interface allowing programmers to 'declare'
76       exception classes at compile time. It also has a base exception class,
77       Exception::Class::Base, that can be easily extended.
78
79       It is designed to make structured exception handling simpler and better
80       by encouraging people to use hierarchies of exceptions in their
81       applications, as opposed to a single catch-all exception class.
82
83       This module does not implement any try/catch syntax. Please see the
84       "OTHER EXCEPTION MODULES (try/catch syntax)" section for more
85       information on how to get this syntax.
86
87       You will also want to look at the documentation for
88       Exception::Class::Base, which is the default base class for all
89       exception objects created by this module.
90

DECLARING EXCEPTION CLASSES

92       Importing "Exception::Class" allows you to automagically create
93       Exception::Class::Base subclasses. You can also create subclasses via
94       the traditional means of defining your own subclass with @ISA.  These
95       two methods may be easily combined, so that you could subclass an
96       exception class defined via the automagic import, if you desired this.
97
98       The syntax for the magic declarations is as follows:
99
100         'MANDATORY CLASS NAME' => \%optional_hashref
101
102       The hashref may contain the following options:
103
104       ·   isa
105
106           This is the class's parent class. If this isn't provided then the
107           class name in $Exception::Class::BASE_EXC_CLASS is assumed to be
108           the parent (see below).
109
110           This parameter lets you create arbitrarily deep class hierarchies.
111           This can be any other Exception::Class::Base subclass in your
112           declaration or a subclass loaded from a module.
113
114           To change the default exception class you will need to change the
115           value of $Exception::Class::BASE_EXC_CLASS before calling "import".
116           To do this simply do something like this:
117
118             BEGIN { $Exception::Class::BASE_EXC_CLASS = 'SomeExceptionClass'; }
119
120           If anyone can come up with a more elegant way to do this please let
121           me know.
122
123           CAVEAT: If you want to automagically subclass an
124           Exception::Class::Base subclass loaded from a file, then you must
125           compile the class (via use or require or some other magic) before
126           you import "Exception::Class" or you'll get a compile time error.
127
128       ·   fields
129
130           This allows you to define additional attributes for your exception
131           class. Any field you define can be passed to the "throw" or "new"
132           methods as additional parameters for the constructor. In addition,
133           your exception object will have an accessor method for the fields
134           you define.
135
136           This parameter can be either a scalar (for a single field) or an
137           array reference if you need to define multiple fields.
138
139           Fields will be inherited by subclasses.
140
141       ·   alias
142
143           Specifying an alias causes this class to create a subroutine of the
144           specified name in the caller's namespace. Calling this subroutine
145           is equivalent to calling "<class>->throw(@_)" for the given
146           exception class.
147
148           Besides convenience, using aliases also allows for additional
149           compile time checking. If the alias is called without parentheses,
150           as in "throw_fields "an error occurred"", then Perl checks for the
151           existence of the "throw_fields" subroutine at compile time. If
152           instead you do "ExceptionWithFields->throw(...)", then Perl checks
153           the class name at runtime, meaning that typos may sneak through.
154
155       ·   description
156
157           Each exception class has a description method that returns a fixed
158           string. This should describe the exception class (as opposed to any
159           particular exception object). This may be useful for debugging if
160           you start catching exceptions you weren't expecting (particularly
161           if someone forgot to document them) and you don't understand the
162           error messages.
163
164       The "Exception::Class" magic attempts to detect circular class
165       hierarchies and will die if it finds one. It also detects missing links
166       in a chain, for example if you declare Bar to be a subclass of Foo and
167       never declare Foo.
168

Try::Tiny

170       If you are interested in adding try/catch/finally syntactic sugar to
171       your code then I recommend you check out Try::Tiny. This is a great
172       module that helps you ignore some of the weirdness with "eval" and $@.
173       Here's an example of how the two modules work together:
174
175         use Exception::Class ( 'My::Exception' );
176         use Scalar::Util qw( blessed );
177         use Try::Tiny;
178
179         try {
180             might_throw();
181         }
182         catch {
183             if ( blessed $_ && $_->isa('My::Exception') ) {
184                 handle_it();
185             }
186             else {
187                 die $_;
188             }
189         };
190
191       Note that you cannot use "Exception::Class->caught" with Try::Tiny.
192

Catching Exceptions Without Try::Tiny

194       "Exception::Class" provides some syntactic sugar for catching
195       exceptions in a safe manner:
196
197         eval {...};
198
199         if ( my $e = Exception::Class->caught('My::Error') ) {
200             cleanup();
201             do_something_with_exception($e);
202         }
203
204       The "caught" method takes a class name and returns an exception object
205       if the last thrown exception is of the given class, or a subclass of
206       that class. If it is not given any arguments, it simply returns $@.
207
208       You should always make a copy of the exception object, rather than
209       using $@ directly. This is necessary because if your "cleanup" function
210       uses "eval", or calls something which uses it, then $@ is overwritten.
211       Copying the exception preserves it for the call to
212       "do_something_with_exception".
213
214       Exception objects also provide a caught method so you can write:
215
216         if ( my $e = My::Error->caught ) {
217             cleanup();
218             do_something_with_exception($e);
219         }
220
221   Uncatchable Exceptions
222       Internally, the "caught" method will call "isa" on the exception
223       object. You could make an exception "uncatchable" by overriding "isa"
224       in that class like this:
225
226        package Exception::Uncatchable;
227
228        sub isa { shift->rethrow }
229
230       Of course, this only works if you always call
231       "Exception::Class->caught" after an "eval".
232

USAGE RECOMMENDATION

234       If you're creating a complex system that throws lots of different types
235       of exceptions, consider putting all the exception declarations in one
236       place. For an app called Foo you might make a "Foo::Exceptions" module
237       and use that in all your code. This module could just contain the code
238       to make "Exception::Class" do its automagic class creation. Doing this
239       allows you to more easily see what exceptions you have, and makes it
240       easier to keep track of them.
241
242       This might look something like this:
243
244         package Foo::Bar::Exceptions;
245
246         use Exception::Class (
247             Foo::Bar::Exception::Senses =>
248                 { description => 'sense-related exception' },
249
250             Foo::Bar::Exception::Smell => {
251                 isa         => 'Foo::Bar::Exception::Senses',
252                 fields      => 'odor',
253                 description => 'stinky!'
254             },
255
256             Foo::Bar::Exception::Taste => {
257                 isa         => 'Foo::Bar::Exception::Senses',
258                 fields      => [ 'taste', 'bitterness' ],
259                 description => 'like, gag me with a spoon!'
260             },
261
262             ...
263         );
264
265       You may want to create a real module to subclass Exception::Class::Base
266       as well, particularly if you want your exceptions to have more methods.
267
268   Subclassing Exception::Class::Base
269       As part of your usage of "Exception::Class", you may want to create
270       your own base exception class which subclasses Exception::Class::Base.
271       You should feel free to subclass any of the methods documented above.
272       For example, you may want to subclass "new" to add additional
273       information to your exception objects.
274

Exception::Class FUNCTIONS

276       The "Exception::Class" method offers one function, "Classes", which is
277       not exported. This method returns a list of the classes that have been
278       created by calling the "Exception::Class" "import" method.  Note that
279       this is all the subclasses that have been created, so it may include
280       subclasses created by things like CPAN modules, etc. Also note that if
281       you simply define a subclass via the normal Perl method of setting @ISA
282       or "use base", then your subclass will not be included.
283

SUPPORT

285       Bugs may be submitted at
286       <https://github.com/houseabsolute/Exception-Class/issues>.
287
288       I am also usually active on IRC as 'autarch' on "irc://irc.perl.org".
289

SOURCE

291       The source code repository for Exception-Class can be found at
292       <https://github.com/houseabsolute/Exception-Class>.
293

DONATIONS

295       If you'd like to thank me for the work I've done on this module, please
296       consider making a "donation" to me via PayPal. I spend a lot of free
297       time creating free software, and would appreciate any support you'd
298       care to offer.
299
300       Please note that I am not suggesting that you must do this in order for
301       me to continue working on this particular software. I will continue to
302       do so, inasmuch as I have in the past, for as long as it interests me.
303
304       Similarly, a donation made in this way will probably not make me work
305       on this software much more, unless I get so many donations that I can
306       consider working on free software full time (let's all have a chuckle
307       at that together).
308
309       To donate, log into PayPal and send money to autarch@urth.org, or use
310       the button at <http://www.urth.org/~autarch/fs-donation.html>.
311

AUTHOR

313       Dave Rolsky <autarch@urth.org>
314

CONTRIBUTORS

316       ·   Alexander Batyrshin <0x62ash@gmail.com>
317
318       ·   Leon Timmermans <fawaka@gmail.com>
319
320       ·   Ricardo Signes <rjbs@cpan.org>
321
323       This software is copyright (c) 2017 by Dave Rolsky.
324
325       This is free software; you can redistribute it and/or modify it under
326       the same terms as the Perl 5 programming language system itself.
327
328       The full text of the license can be found in the LICENSE file included
329       with this distribution.
330
331
332
333perl v5.28.1                      2017-12-10               Exception::Class(3)
Impressum