1Exception::Class(3) User Contributed Perl Documentation Exception::Class(3)
2
3
4
6 Exception::Class - A module that allows you to declare real exception
7 classes in Perl
8
10 version 1.45
11
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
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
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 Each field name must be a legal Perl identifier: it starts with a
140 ASCII letter or underscore, and is followed by zero or more ASCII
141 letters, ASCII digits, or underscores. If a field name does not
142 match this, the creation of that exception class croaks.
143
144 Fields will be inherited by subclasses.
145
146 • alias
147
148 Specifying an alias causes this class to create a subroutine of the
149 specified name in the caller's namespace. Calling this subroutine
150 is equivalent to calling "<class>->throw(@_)" for the given
151 exception class.
152
153 Besides convenience, using aliases also allows for additional
154 compile time checking. If the alias is called without parentheses,
155 as in throw_fields "an error occurred", then Perl checks for the
156 existence of the "throw_fields" subroutine at compile time. If
157 instead you do "ExceptionWithFields->throw(...)", then Perl checks
158 the class name at runtime, meaning that typos may sneak through.
159
160 • description
161
162 Each exception class has a description method that returns a fixed
163 string. This should describe the exception class (as opposed to any
164 particular exception object). This may be useful for debugging if
165 you start catching exceptions you weren't expecting (particularly
166 if someone forgot to document them) and you don't understand the
167 error messages.
168
169 The "Exception::Class" magic attempts to detect circular class
170 hierarchies and will die if it finds one. It also detects missing links
171 in a chain, for example if you declare Bar to be a subclass of Foo and
172 never declare Foo.
173
175 If you are interested in adding try/catch/finally syntactic sugar to
176 your code then I recommend you check out Try::Tiny. This is a great
177 module that helps you ignore some of the weirdness with "eval" and $@.
178 Here's an example of how the two modules work together:
179
180 use Exception::Class ( 'My::Exception' );
181 use Scalar::Util qw( blessed );
182 use Try::Tiny;
183
184 try {
185 might_throw();
186 }
187 catch {
188 if ( blessed $_ && $_->isa('My::Exception') ) {
189 handle_it();
190 }
191 else {
192 die $_;
193 }
194 };
195
196 Note that you cannot use "Exception::Class->caught" with Try::Tiny.
197
199 "Exception::Class" provides some syntactic sugar for catching
200 exceptions in a safe manner:
201
202 eval {...};
203
204 if ( my $e = Exception::Class->caught('My::Error') ) {
205 cleanup();
206 do_something_with_exception($e);
207 }
208
209 The "caught" method takes a class name and returns an exception object
210 if the last thrown exception is of the given class, or a subclass of
211 that class. If it is not given any arguments, it simply returns $@.
212
213 You should always make a copy of the exception object, rather than
214 using $@ directly. This is necessary because if your "cleanup" function
215 uses "eval", or calls something which uses it, then $@ is overwritten.
216 Copying the exception preserves it for the call to
217 "do_something_with_exception".
218
219 Exception objects also provide a caught method so you can write:
220
221 if ( my $e = My::Error->caught ) {
222 cleanup();
223 do_something_with_exception($e);
224 }
225
226 Uncatchable Exceptions
227 Internally, the "caught" method will call "isa" on the exception
228 object. You could make an exception "uncatchable" by overriding "isa"
229 in that class like this:
230
231 package Exception::Uncatchable;
232
233 sub isa { shift->rethrow }
234
235 Of course, this only works if you always call
236 "Exception::Class->caught" after an "eval".
237
239 If you're creating a complex system that throws lots of different types
240 of exceptions, consider putting all the exception declarations in one
241 place. For an app called Foo you might make a "Foo::Exceptions" module
242 and use that in all your code. This module could just contain the code
243 to make "Exception::Class" do its automagic class creation. Doing this
244 allows you to more easily see what exceptions you have, and makes it
245 easier to keep track of them.
246
247 This might look something like this:
248
249 package Foo::Bar::Exceptions;
250
251 use Exception::Class (
252 Foo::Bar::Exception::Senses =>
253 { description => 'sense-related exception' },
254
255 Foo::Bar::Exception::Smell => {
256 isa => 'Foo::Bar::Exception::Senses',
257 fields => 'odor',
258 description => 'stinky!'
259 },
260
261 Foo::Bar::Exception::Taste => {
262 isa => 'Foo::Bar::Exception::Senses',
263 fields => [ 'taste', 'bitterness' ],
264 description => 'like, gag me with a spoon!'
265 },
266
267 ...
268 );
269
270 You may want to create a real module to subclass Exception::Class::Base
271 as well, particularly if you want your exceptions to have more methods.
272
273 Subclassing Exception::Class::Base
274 As part of your usage of "Exception::Class", you may want to create
275 your own base exception class which subclasses Exception::Class::Base.
276 You should feel free to subclass any of the methods documented above.
277 For example, you may want to subclass "new" to add additional
278 information to your exception objects.
279
281 The "Exception::Class" method offers one function, "Classes", which is
282 not exported. This method returns a list of the classes that have been
283 created by calling the "Exception::Class" "import" method. Note that
284 this is all the subclasses that have been created, so it may include
285 subclasses created by things like CPAN modules, etc. Also note that if
286 you simply define a subclass via the normal Perl method of setting @ISA
287 or "use base", then your subclass will not be included.
288
290 Bugs may be submitted at
291 <https://github.com/houseabsolute/Exception-Class/issues>.
292
293 I am also usually active on IRC as 'autarch' on "irc://irc.perl.org".
294
296 The source code repository for Exception-Class can be found at
297 <https://github.com/houseabsolute/Exception-Class>.
298
300 If you'd like to thank me for the work I've done on this module, please
301 consider making a "donation" to me via PayPal. I spend a lot of free
302 time creating free software, and would appreciate any support you'd
303 care to offer.
304
305 Please note that I am not suggesting that you must do this in order for
306 me to continue working on this particular software. I will continue to
307 do so, inasmuch as I have in the past, for as long as it interests me.
308
309 Similarly, a donation made in this way will probably not make me work
310 on this software much more, unless I get so many donations that I can
311 consider working on free software full time (let's all have a chuckle
312 at that together).
313
314 To donate, log into PayPal and send money to autarch@urth.org, or use
315 the button at <https://www.urth.org/fs-donation.html>.
316
318 Dave Rolsky <autarch@urth.org>
319
321 • Alexander Batyrshin <0x62ash@gmail.com>
322
323 • brian d foy <brian.d.foy@gmail.com>
324
325 • Leon Timmermans <fawaka@gmail.com>
326
327 • Ricardo Signes <rjbs@cpan.org>
328
330 This software is copyright (c) 2021 by Dave Rolsky.
331
332 This is free software; you can redistribute it and/or modify it under
333 the same terms as the Perl 5 programming language system itself.
334
335 The full text of the license can be found in the LICENSE file included
336 with this distribution.
337
338
339
340perl v5.38.0 2023-07-20 Exception::Class(3)