1Error(3)              User Contributed Perl Documentation             Error(3)
2
3
4

NAME

6       Error - Error/exception handling in an OO-ish way
7

WARNING

9       Using the "Error" module is no longer recommended due to the black-
10       magical nature of its syntactic sugar, which often tends to break. Its
11       maintainers have stopped actively writing code that uses it, and
12       discourage people from doing so. See the "SEE ALSO" section below for
13       better recommendations.
14

SYNOPSIS

16           use Error qw(:try);
17
18           throw Error::Simple( "A simple error");
19
20           sub xyz {
21               ...
22               record Error::Simple("A simple error")
23                   and return;
24           }
25
26           unlink($file) or throw Error::Simple("$file: $!",$!);
27
28           try {
29               do_some_stuff();
30               die "error!" if $condition;
31               throw Error::Simple "Oops!" if $other_condition;
32           }
33           catch Error::IO with {
34               my $E = shift;
35               print STDERR "File ", $E->{'-file'}, " had a problem\n";
36           }
37           except {
38               my $E = shift;
39               my $general_handler=sub {send_message $E->{-description}};
40               return {
41                   UserException1 => $general_handler,
42                   UserException2 => $general_handler
43               };
44           }
45           otherwise {
46               print STDERR "Well I don't know what to say\n";
47           }
48           finally {
49               close_the_garage_door_already(); # Should be reliable
50           }; # Don't forget the trailing ; or you might be surprised
51

DESCRIPTION

53       The "Error" package provides two interfaces. Firstly "Error" provides a
54       procedural interface to exception handling. Secondly "Error" is a base
55       class for errors/exceptions that can either be thrown, for subsequent
56       catch, or can simply be recorded.
57
58       Errors in the class "Error" should not be thrown directly, but the user
59       should throw errors from a sub-class of "Error".
60

PROCEDURAL INTERFACE

62       "Error" exports subroutines to perform exception handling. These will
63       be exported if the ":try" tag is used in the "use" line.
64
65       try BLOCK CLAUSES
66           "try" is the main subroutine called by the user. All other
67           subroutines exported are clauses to the try subroutine.
68
69           The BLOCK will be evaluated and, if no error is throw, try will
70           return the result of the block.
71
72           "CLAUSES" are the subroutines below, which describe what to do in
73           the event of an error being thrown within BLOCK.
74
75       catch CLASS with BLOCK
76           This clauses will cause all errors that satisfy "$err->isa(CLASS)"
77           to be caught and handled by evaluating "BLOCK".
78
79           "BLOCK" will be passed two arguments. The first will be the error
80           being thrown. The second is a reference to a scalar variable. If
81           this variable is set by the catch block then, on return from the
82           catch block, try will continue processing as if the catch block was
83           never found. The error will also be available in $@.
84
85           To propagate the error the catch block may call "$err->throw"
86
87           If the scalar reference by the second argument is not set, and the
88           error is not thrown. Then the current try block will return with
89           the result from the catch block.
90
91       except BLOCK
92           When "try" is looking for a handler, if an except clause is found
93           "BLOCK" is evaluated. The return value from this block should be a
94           HASHREF or a list of key-value pairs, where the keys are class
95           names and the values are CODE references for the handler of errors
96           of that type.
97
98       otherwise BLOCK
99           Catch any error by executing the code in "BLOCK"
100
101           When evaluated "BLOCK" will be passed one argument, which will be
102           the error being processed. The error will also be available in $@.
103
104           Only one otherwise block may be specified per try block
105
106       finally BLOCK
107           Execute the code in "BLOCK" either after the code in the try block
108           has successfully completed, or if the try block throws an error
109           then "BLOCK" will be executed after the handler has completed.
110
111           If the handler throws an error then the error will be caught, the
112           finally block will be executed and the error will be re-thrown.
113
114           Only one finally block may be specified per try block
115

COMPATIBILITY

117       Moose exports a keyword called "with" which clashes with Error's. This
118       example returns a prototype mismatch error:
119
120           package MyTest;
121
122           use warnings;
123           use Moose;
124           use Error qw(:try);
125
126       (Thanks to "maik.hentsche@amd.com" for the report.).
127

CLASS INTERFACE

129   CONSTRUCTORS
130       The "Error" object is implemented as a HASH. This HASH is initialized
131       with the arguments that are passed to it's constructor. The elements
132       that are used by, or are retrievable by the "Error" class are listed
133       below, other classes may add to these.
134
135               -file
136               -line
137               -text
138               -value
139               -object
140
141       If "-file" or "-line" are not specified in the constructor arguments
142       then these will be initialized with the file name and line number where
143       the constructor was called from.
144
145       If the error is associated with an object then the object should be
146       passed as the "-object" argument. This will allow the "Error" package
147       to associate the error with the object.
148
149       The "Error" package remembers the last error created, and also the last
150       error associated with a package. This could either be the last error
151       created by a sub in that package, or the last error which passed an
152       object blessed into that package as the "-object" argument.
153
154       Error->new()
155           See the Error::Simple documentation.
156
157       throw ( [ ARGS ] )
158           Create a new "Error" object and throw an error, which will be
159           caught by a surrounding "try" block, if there is one. Otherwise it
160           will cause the program to exit.
161
162           "throw" may also be called on an existing error to re-throw it.
163
164       with ( [ ARGS ] )
165           Create a new "Error" object and returns it. This is defined for
166           syntactic sugar, eg
167
168               die with Some::Error ( ... );
169
170       record ( [ ARGS ] )
171           Create a new "Error" object and returns it. This is defined for
172           syntactic sugar, eg
173
174               record Some::Error ( ... )
175                   and return;
176
177   STATIC METHODS
178       prior ( [ PACKAGE ] )
179           Return the last error created, or the last error associated with
180           "PACKAGE"
181
182       flush ( [ PACKAGE ] )
183           Flush the last error created, or the last error associated with
184           "PACKAGE".It is necessary to clear the error stack before exiting
185           the package or uncaught errors generated using "record" will be
186           reported.
187
188                $Error->flush;
189
190   OBJECT METHODS
191       stacktrace
192           If the variable $Error::Debug was non-zero when the error was
193           created, then "stacktrace" returns a string created by calling
194           "Carp::longmess". If the variable was zero the "stacktrace" returns
195           the text of the error appended with the filename and line number of
196           where the error was created, providing the text does not end with a
197           newline.
198
199       object
200           The object this error was associated with
201
202       file
203           The file where the constructor of this error was called from
204
205       line
206           The line where the constructor of this error was called from
207
208       text
209           The text of the error
210
211       $err->associate($obj)
212           Associates an error with an object to allow error propagation. I.e:
213
214               $ber->encode(...) or
215                   return Error->prior($ber)->associate($ldap);
216
217   OVERLOAD METHODS
218       stringify
219           A method that converts the object into a string. This method may
220           simply return the same as the "text" method, or it may append more
221           information. For example the file name and line number.
222
223           By default this method returns the "-text" argument that was passed
224           to the constructor, or the string "Died" if none was given.
225
226       value
227           A method that will return a value that can be associated with the
228           error. For example if an error was created due to the failure of a
229           system call, then this may return the numeric value of $! at the
230           time.
231
232           By default this method returns the "-value" argument that was
233           passed to the constructor.
234

PRE-DEFINED ERROR CLASSES

236   Error::Simple
237       This class can be used to hold simple error strings and values. It's
238       constructor takes two arguments. The first is a text value, the second
239       is a numeric value. These values are what will be returned by the
240       overload methods.
241
242       If the text value ends with "at file line 1" as $@ strings do, then
243       this information will be used to set the "-file" and "-line" arguments
244       of the error object.
245
246       This class is used internally if an eval'd block die's with an error
247       that is a plain string. (Unless $Error::ObjectifyCallback is modified)
248

$Error::ObjectifyCallback

250       This variable holds a reference to a subroutine that converts errors
251       that are plain strings to objects. It is used by Error.pm to convert
252       textual errors to objects, and can be overridden by the user.
253
254       It accepts a single argument which is a hash reference to named
255       parameters.  Currently the only named parameter passed is 'text' which
256       is the text of the error, but others may be available in the future.
257
258       For example the following code will cause Error.pm to throw objects of
259       the class MyError::Bar by default:
260
261           sub throw_MyError_Bar
262           {
263               my $args = shift;
264               my $err = MyError::Bar->new();
265               $err->{'MyBarText'} = $args->{'text'};
266               return $err;
267           }
268
269           {
270               local $Error::ObjectifyCallback = \&throw_MyError_Bar;
271
272               # Error handling here.
273           }
274

MESSAGE HANDLERS

276       "Error" also provides handlers to extend the output of the "warn()"
277       perl function, and to handle the printing of a thrown "Error" that is
278       not caught or otherwise handled. These are not installed by default,
279       but are requested using the ":warndie" tag in the "use" line.
280
281        use Error qw( :warndie );
282
283       These new error handlers are installed in $SIG{__WARN__} and
284       $SIG{__DIE__}. If these handlers are already defined when the tag is
285       imported, the old values are stored, and used during the new code.
286       Thus, to arrange for custom handling of warnings and errors, you will
287       need to perform something like the following:
288
289        BEGIN {
290          $SIG{__WARN__} = sub {
291            print STDERR "My special warning handler: $_[0]"
292          };
293        }
294
295        use Error qw( :warndie );
296
297       Note that setting $SIG{__WARN__} after the ":warndie" tag has been
298       imported will overwrite the handler that "Error" provides. If this
299       cannot be avoided, then the tag can be explicitly "import"ed later
300
301        use Error;
302
303        $SIG{__WARN__} = ...;
304
305        import Error qw( :warndie );
306
307   EXAMPLE
308       The "__DIE__" handler turns messages such as
309
310        Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
311
312       into
313
314        Unhandled perl error caught at toplevel:
315
316          Can't call method "foo" on an undefined value
317
318        Thrown from: examples/warndie.pl:16
319
320        Full stack trace:
321
322                main::inner('undef') called at examples/warndie.pl line 20
323                main::outer('undef') called at examples/warndie.pl line 23
324

SEE ALSO

326       See Exception::Class for a different module providing Object-Oriented
327       exception handling, along with a convenient syntax for declaring
328       hierarchies for them. It doesn't provide Error's syntactic sugar of
329       "try { ... }", "catch { ... }", etc. which may be a good thing or a bad
330       thing based on what you want. (Because Error's syntactic sugar tends to
331       break.)
332
333       Error::Exception aims to combine Error and Exception::Class "with
334       correct stringification".
335
336       TryCatch and Try::Tiny are similar in concept to Error.pm only
337       providing a syntax that hopefully breaks less.
338

KNOWN BUGS

340       None, but that does not mean there are not any.
341

AUTHORS

343       Graham Barr <gbarr@pobox.com>
344
345       The code that inspired me to write this was originally written by Peter
346       Seibel <peter@weblogic.com> and adapted by Jesse Glick
347       <jglick@sig.bsh.com>.
348
349       ":warndie" handlers added by Paul Evans <leonerd@leonerd.org.uk>
350

MAINTAINER

352       Shlomi Fish, <http://www.shlomifish.org/> .
353

PAST MAINTAINERS

355       Arun Kumar U <u_arunkumar@yahoo.com>
356
358       Copyright (c) 1997-8  Graham Barr. All rights reserved.  This program
359       is free software; you can redistribute it and/or modify it under the
360       same terms as Perl itself.
361
362
363
364perl v5.16.3                      2014-06-09                          Error(3)
Impressum