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

NAME

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

SYNOPSIS

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

DESCRIPTION

46       The "Error" package provides two interfaces. Firstly "Error" provides a
47       procedural interface to exception handling. Secondly "Error" is a base
48       class for errors/exceptions that can either be thrown, for subsequent
49       catch, or can simply be recorded.
50
51       Errors in the class "Error" should not be thrown directly, but the user
52       should throw errors from a sub-class of "Error".
53

PROCEDURAL INTERFACE

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

CLASS INTERFACE

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

PRE-DEFINED ERROR CLASSES

217   Error::Simple
218       This class can be used to hold simple error strings and values. It's
219       constructor takes two arguments. The first is a text value, the second
220       is a numeric value. These values are what will be returned by the
221       overload methods.
222
223       If the text value ends with "at file line 1" as $@ strings do, then
224       this infomation will be used to set the "-file" and "-line" arguments
225       of the error object.
226
227       This class is used internally if an eval'd block die's with an error
228       that is a plain string. (Unless $Error::ObjectifyCallback is modified)
229

$Error::ObjectifyCallback

231       This variable holds a reference to a subroutine that converts errors
232       that are plain strings to objects. It is used by Error.pm to convert
233       textual errors to objects, and can be overrided by the user.
234
235       It accepts a single argument which is a hash reference to named
236       parameters.  Currently the only named parameter passed is 'text' which
237       is the text of the error, but others may be available in the future.
238
239       For example the following code will cause Error.pm to throw objects of
240       the class MyError::Bar by default:
241
242           sub throw_MyError_Bar
243           {
244               my $args = shift;
245               my $err = MyError::Bar->new();
246               $err->{'MyBarText'} = $args->{'text'};
247               return $err;
248           }
249
250           {
251               local $Error::ObjectifyCallback = \&throw_MyError_Bar;
252
253               # Error handling here.
254           }
255

MESSAGE HANDLERS

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

SEE ALSO

307       See Exception::Class for a different module providing Object-Oriented
308       exception handling, along with a convenient syntax for declaring
309       hierarchies for them. It doesn't provide Error's syntactic sugar of
310       "try { ... }", "catch { ... }", etc. which may be a good thing or a bad
311       thing based on what you want. (Because Error's syntactic sugar tends to
312       break.)
313
314       Error::Exception aims to combine Error and Exception::Class "with
315       correct stringification".
316

KNOWN BUGS

318       None, but that does not mean there are not any.
319

AUTHORS

321       Graham Barr <gbarr@pobox.com>
322
323       The code that inspired me to write this was originally written by Peter
324       Seibel <peter@weblogic.com> and adapted by Jesse Glick
325       <jglick@sig.bsh.com>.
326
327       ":warndie" handlers added by Paul Evans <leonerd@leonerd.org.uk>
328

MAINTAINER

330       Shlomi Fish <shlomif@iglu.org.il>
331

PAST MAINTAINERS

333       Arun Kumar U <u_arunkumar@yahoo.com>
334
336       Copyright (c) 1997-8  Graham Barr. All rights reserved.  This program
337       is free software; you can redistribute it and/or modify it under the
338       same terms as Perl itself.
339
340
341
342perl v5.10.1                      2010-08-20                          Error(3)
Impressum