Error(3)
π Error(3) π
okay bestie, welcome to the Error(3) page from User Contributed Perl Documentation. Itβs giving βexception handling in an OO-ish way,β and ngl the vintage Perl energy is iconic. Letβs get into it. π«Ά
π NAME π
Error β Error/exception handling in an OO-ish way.
π VERSION π
version 0.17030. Slay.
β¨ SYNOPSIS β¨
use Error qw(:try);
throw Error::Simple( "A simple error");
sub xyz {
...
record Error::Simple("A simple error")
and return;
}
unlink($file) or throw Error::Simple("$file: $!",$!);
try {
do_some_stuff();
die "error!" if $condition;
throw Error::Simple "Oops!" if $other_condition;
}
catch Error::IO with {
my $E = shift;
print STDERR "File ", $E->{'-file'}, " had a problem\n";
}
except {
my $E = shift;
my $general_handler=sub {send_message $E->{-description}};
return {
UserException1 => $general_handler,
UserException2 => $general_handler
};
}
otherwise {
print STDERR "Well I don't know what to say\n";
}
finally {
close_the_garage_door_already(); # Should be reliable
}; # Don't forget the trailing ; or you might be surprised
π DESCRIPTION π
The Error package provides two interfaces. First, Error gives a procedural interface to exception handling. Second, Error is a base class for errors/exceptions that can either be thrown, for later catch, or can simply be recorded.
Errors in the class Error should not be thrown directly β bestie, the user should throw errors from a sub-class of Error.
π¨ WARNING π¨
Using the Error module is no longer recommended β not in a cute way. Itβs because of the black-magical nature of its syntactic sugar, which often tends to break. Its maintainers have stopped actively writing code that uses it, and they discourage people from doing so. See the SEE ALSO section below for better recommendations. periodt.
π§ͺ PROCEDURAL INTERFACE π§ͺ
Error exports subroutines to perform exception handling. These will be exported if the :try tag is used in the use line.
π try BLOCK CLAUSES π
try is the main subroutine called by the user. All the other subroutines exported are clauses to the try subroutine.
The BLOCK will be evaluated and, if no error is thrown, try will return the result of the block.
CLAUSES are the subroutines below, which describe what to do in the event of an error being thrown within BLOCK.
π― catch CLASS with BLOCK π―
This clause will cause all errors that satisfy $err->isa(CLASS) to be caught and handled by evaluating BLOCK.
BLOCK will be passed two arguments. The first will be the error being thrown. The second is a reference to a scalar variable. If this variable is set by the catch block then, on return from the catch block, try will continue processing as if the catch block was never found. The error will also be available in $@.
To propagate the error the catch block may call $err->throw.
If the scalar reference by the second argument is not set, and the error is not thrown. Then the current try block will return with the result from the catch block.
π«§ except BLOCK π«§
When try is looking for a handler, if an except clause is found BLOCK is evaluated. The return value from this block should be a HASHREF or a list of key-value pairs, where the keys are class names and the values are CODE references for the handler of errors of that type.
πΈ otherwise BLOCK πΈ
Catch any error by executing the code in BLOCK.
When evaluated BLOCK will be passed one argument, which will be the error being processed. The error will also be available in $@.
Only one otherwise block may be specified per try block.
π finally BLOCK π
Execute the code in BLOCK either after the code in the try block has successfully completed, or if the try block throws an error then BLOCK will be executed after the handler has completed.
If the handler throws an error then the error will be caught, the finally block will be executed and the error will be re-thrown.
Only one finally block may be specified per try block.
π€ COMPATIBILITY π€
Moose exports a keyword called with which clashes with Error's. This example returns a prototype mismatch error:
package MyTest;
use warnings;
use Moose;
use Error qw(:try);
(Thanks to maik.hentsche@amd.com for the report.).
π οΈ CLASS INTERFACE π οΈ
π§΅ CONSTRUCTORS π§΅
The Error object is implemented as a HASH. This HASH is initialized with the arguments that are passed to its constructor. The elements that are used by, or are retrievable by, the Error class are listed below β other classes may add to these.
-file-line-text-value-object
If -file or -line are not specified in the constructor arguments then these will be initialized with the file name and line number where the constructor was called from.
If the error is associated with an object then the object should be passed as the -object argument. This will allow the Error package to associate the error with the object.
The Error package remembers the last error created, and also the last error associated with a package. This could either be the last error created by a sub in that package, or the last error which passed an object blessed into that package as the -object argument.
Error->new()β See theError::Simpledocumentation.throw ( [ ARGS ] )β Create a newErrorobject and throw an error, which will be caught by a surroundingtryblock, if there is one. Otherwise it will cause the program to exit.throwmay also be called on an existing error to re-throw it.with ( [ ARGS ] )β Create a newErrorobject and returns it. This is defined for syntactic sugar, egdie with Some::Error ( ... );record ( [ ARGS ] )β Create a newErrorobject and returns it. This is defined for syntactic sugar, eg:
record Some::Error ( ... )
and return;
π STATIC METHODS π
prior ( [ PACKAGE ] )β Return the last error created, or the last error associated withPACKAGE.flush ( [ PACKAGE ] )β Flush the last error created, or the last error associated withPACKAGE. It is necessary to clear the error stack before exiting the package or uncaught errors generated usingrecordwill be reported.
$Error->flush;
π OBJECT METHODS π
stacktraceβ If the variable$Error::Debugwas non-zero when the error was created, thenstacktracereturns a string created by callingCarp::longmess. If the variable was zero thestacktracereturns the text of the error appended with the filename and line number of where the error was created, providing the text does not end with a newline.objectβ The object this error was associated with.fileβ The file where the constructor of this error was called from.lineβ The line where the constructor of this error was called from.textβ The text of the error.$err->associate($obj)β Associates an error with an object to allow error propagation. I.e:
$ber->encode(...) or
return Error->prior($ber)->associate($ldap);
π OVERLOAD METHODS π
stringifyβ A method that converts the object into a string. This method may simply return the same as thetextmethod, or it may append more information. For example the file name and line number. By default this method returns the-textargument that was passed to the constructor, or the string"Died"if none was given.valueβ A method that will return a value that can be associated with the error. For example if an error was created due to the failure of a system call, then this may return the numeric value of$!at the time. By default this method returns the-valueargument that was passed to the constructor.
π§ PRE-DEFINED ERROR CLASSES π§
π§Έ Error::Simple π§Έ
This class can be used to hold simple error strings and values. It's constructor takes two arguments. The first is a text value, the second is a numeric value. These values are what will be returned by the overload methods.
If the text value ends with at file line 1 as $@ strings do, then this information will be used to set the -file and -line arguments of the error object.
This class is used internally if an eval'd block die's with an error that is a plain string. (Unless $Error::ObjectifyCallback is modified)
π $Error::ObjectifyCallback π
This variable holds a reference to a subroutine that converts errors that are plain strings to objects. It is used by Error.pm to convert textual errors to objects, and can be overridden by the user.
It accepts a single argument which is a hash reference to named parameters. Currently the only named parameter passed is 'text' which is the text of the error, but others may be available in the future.
For example the following code will cause Error.pm to throw objects of the class MyError::Bar by default:
sub throw_MyError_Bar
{
my $args = shift;
my $err = MyError::Bar->new();
$err->{'MyBarText'} = $args->{'text'};
return $err;
}
{
local $Error::ObjectifyCallback = \&throw_MyError_Bar;
# Error handling here.
}
π MESSAGE HANDLERS π
okay so Error ALSO provides handlers to extend the output of the warn() perl function, plus handlers for printing a thrown Error that isn't caught or otherwise handled. These are not installed by default, but are requested using the :warndie tag in the use line:
use Error qw( :warndie );
These new error handlers are installed in $SIG{__WARN__} and $SIG{__DIE__}. If these handlers are already defined when the tag is imported, the old values are stored, and used during the new code. Thus, to arrange for custom handling of warnings and errors, you will need to perform something like the following:
BEGIN {
$SIG{__WARN__} = sub {
print STDERR "My special warning handler: $_[0]"
};
}
use Error qw( :warndie );
girlie pop heads up: setting$SIG{__WARN__}after the:warndietag has been imported will overwrite the handler thatErrorprovides. If this cannot be avoided, then the tag can be explicitlyimported later:
use Error;
$SIG{__WARN__} = ...;
import Error qw( :warndie );
π EXAMPLE π
The __DIE__ handler turns messages such as:
Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
into this whole glow-up:
Unhandled perl error caught at toplevel:
Can't call method "foo" on an undefined value
Thrown from: examples/warndie.pl:16
Full stack trace:
main::inner('undef') called at examples/warndie.pl line 20
main::outer('undef') called at examples/warndie.pl line 23
π SEE ALSO π
See Exception::Class for a different module providing Object-Oriented exception handling, along with a convenient syntax for declaring hierarchies for them. It doesn't provide Error's syntactic sugar of try { ... }, catch { ... }, etc. which may be a good thing or a bad thing based on what you want. (Because Error's syntactic sugar tends to break.) π
Error::Exception aims to combine Error and Exception::Class "with correct stringification".
TryCatch and Try::Tiny are similar in concept to Error.pm only providing a syntax that hopefully breaks less.
π KNOWN BUGS π
None, but that does not mean there are not any. iykyk π
π AUTHORS π
Graham Barr <gbarr@pobox.com>
The code that inspired me to write this was originally written by Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.
:warndie handlers added by Paul Evans <leonerd@leonerd.org.uk>
π οΈ MAINTAINER π οΈ
Shlomi Fish, <http://www.shlomifish.org/> .
π PAST MAINTAINERS π
Arun Kumar U <u_arunkumar@yahoo.com>
Β©οΈ COPYRIGHT Β©οΈ
Copyright (c) 1997-8 Graham Barr. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
π«Ά SUPPORT π«Ά
π Websites π
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
- MetaCPAN β a modern, open-source CPAN search engine, useful to view POD in HTML format.
<https://metacpan.org/release/Error> - RT: CPAN's Bug Tracker β the RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
<https://rt.cpan.org/Public/Dist/Display.html?Name=Error> - CPANTS β the CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
<http://cpants.cpanauthors.org/dist/Error> - CPAN Testers β the CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
<http://www.cpantesters.org/distro/E/Error> - CPAN Testers Matrix β the CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
<http://matrix.cpantesters.org/?dist=Error> - CPAN Testers Dependencies β the CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
<http://deps.cpantesters.org/?module=Error>
π Bugs / Feature Requests π
Please report any bugs or feature requests by email to bug-error at rt.cpan.org, or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Error>. You will be automatically notified of any progress on the request by the system.
π§ Source Code π§
The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)
<https://github.com/shlomif/perl-error.pm>
git clone git://github.com/shlomif/perl-error.pm.git
π AUTHOR π
Shlomi Fish ( http://www.shlomifish.org/ )
π BUGS π
Please report any bugs or feature requests on the bugtracker website <https://github.com/shlomif/perl-error.pm/issues>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2025 by Shlomi Fish ( http://www.shlomifish.org/ ).
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
k bye bestie β source/version perl v5.42.0, date 2025-07-25, page Error(3). slay forever π
β¨
π¦ where this page comes from
- fedora 43: perl-Error 1:0.17030-2.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND X11
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms