{
    "mode": "perldoc",
    "parameter": "Error",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Error/json",
    "generated": "2026-06-15T14:36:39Z",
    "synopsis": "use Error qw(:try);\nthrow Error::Simple( \"A simple error\");\nsub xyz {\n...\nrecord Error::Simple(\"A simple error\")\nand return;\n}\nunlink($file) or throw Error::Simple(\"$file: $!\",$!);\ntry {\ndosomestuff();\ndie \"error!\" if $condition;\nthrow Error::Simple \"Oops!\" if $othercondition;\n}\ncatch Error::IO with {\nmy $E = shift;\nprint STDERR \"File \", $E->{'-file'}, \" had a problem\\n\";\n}\nexcept {\nmy $E = shift;\nmy $generalhandler=sub {sendmessage $E->{-description}};\nreturn {\nUserException1 => $generalhandler,\nUserException2 => $generalhandler\n};\n}\notherwise {\nprint STDERR \"Well I don't know what to say\\n\";\n}\nfinally {\nclosethegaragedooralready(); # Should be reliable\n}; # Don't forget the trailing ; or you might be surprised",
    "sections": {
        "NAME": {
            "content": "Error - Error/exception handling in an OO-ish way\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 0.17029\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Error qw(:try);\n\nthrow Error::Simple( \"A simple error\");\n\nsub xyz {\n...\nrecord Error::Simple(\"A simple error\")\nand return;\n}\n\nunlink($file) or throw Error::Simple(\"$file: $!\",$!);\n\ntry {\ndosomestuff();\ndie \"error!\" if $condition;\nthrow Error::Simple \"Oops!\" if $othercondition;\n}\ncatch Error::IO with {\nmy $E = shift;\nprint STDERR \"File \", $E->{'-file'}, \" had a problem\\n\";\n}\nexcept {\nmy $E = shift;\nmy $generalhandler=sub {sendmessage $E->{-description}};\nreturn {\nUserException1 => $generalhandler,\nUserException2 => $generalhandler\n};\n}\notherwise {\nprint STDERR \"Well I don't know what to say\\n\";\n}\nfinally {\nclosethegaragedooralready(); # Should be reliable\n}; # Don't forget the trailing ; or you might be surprised\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The \"Error\" package provides two interfaces. Firstly \"Error\" provides a procedural interface to\nexception handling. Secondly \"Error\" is a base class for errors/exceptions that can either be\nthrown, for subsequent catch, or can simply be recorded.\n\nErrors in the class \"Error\" should not be thrown directly, but the user should throw errors from\na sub-class of \"Error\".\n",
            "subsections": []
        },
        "WARNING": {
            "content": "Using the \"Error\" module is no longer recommended due to the black-magical nature of its\nsyntactic sugar, which often tends to break. Its maintainers have stopped actively writing code\nthat uses it, and discourage people from doing so. See the \"SEE ALSO\" section below for better\nrecommendations.\n",
            "subsections": []
        },
        "PROCEDURAL INTERFACE": {
            "content": "\"Error\" exports subroutines to perform exception handling. These will be exported if the \":try\"\ntag is used in the \"use\" line.\n\ntry BLOCK CLAUSES\n\"try\" is the main subroutine called by the user. All other subroutines exported are clauses\nto the try subroutine.\n\nThe BLOCK will be evaluated and, if no error is throw, try will return the result of the\nblock.\n\n\"CLAUSES\" are the subroutines below, which describe what to do in the event of an error\nbeing thrown within BLOCK.\n\ncatch CLASS with BLOCK\nThis clauses will cause all errors that satisfy \"$err->isa(CLASS)\" to be caught and handled\nby evaluating \"BLOCK\".\n\n\"BLOCK\" will be passed two arguments. The first will be the error being thrown. The second\nis a reference to a scalar variable. If this variable is set by the catch block then, on\nreturn from the catch block, try will continue processing as if the catch block was never\nfound. The error will also be available in $@.\n\nTo propagate the error the catch block may call \"$err->throw\"\n\nIf the scalar reference by the second argument is not set, and the error is not thrown. Then\nthe current try block will return with the result from the catch block.\n\nexcept BLOCK\nWhen \"try\" is looking for a handler, if an except clause is found \"BLOCK\" is evaluated. The\nreturn value from this block should be a HASHREF or a list of key-value pairs, where the\nkeys are class names and the values are CODE references for the handler of errors of that\ntype.\n\notherwise BLOCK\nCatch any error by executing the code in \"BLOCK\"\n\nWhen evaluated \"BLOCK\" will be passed one argument, which will be the error being processed.\nThe error will also be available in $@.\n\nOnly one otherwise block may be specified per try block\n\nfinally BLOCK\nExecute the code in \"BLOCK\" either after the code in the try block has successfully\ncompleted, or if the try block throws an error then \"BLOCK\" will be executed after the\nhandler has completed.\n\nIf the handler throws an error then the error will be caught, the finally block will be\nexecuted and the error will be re-thrown.\n\nOnly one finally block may be specified per try block\n",
            "subsections": []
        },
        "COMPATIBILITY": {
            "content": "Moose exports a keyword called \"with\" which clashes with Error's. This example returns a\nprototype mismatch error:\n\npackage MyTest;\n\nuse warnings;\nuse Moose;\nuse Error qw(:try);\n\n(Thanks to \"maik.hentsche@amd.com\" for the report.).\n",
            "subsections": []
        },
        "CLASS INTERFACE": {
            "content": "CONSTRUCTORS\nThe \"Error\" object is implemented as a HASH. This HASH is initialized with the arguments that\nare passed to it's constructor. The elements that are used by, or are retrievable by the \"Error\"\nclass are listed below, other classes may add to these.\n\n-file\n-line\n-text\n-value\n-object\n\nIf \"-file\" or \"-line\" are not specified in the constructor arguments then these will be\ninitialized with the file name and line number where the constructor was called from.\n\nIf the error is associated with an object then the object should be passed as the \"-object\"\nargument. This will allow the \"Error\" package to associate the error with the object.\n\nThe \"Error\" package remembers the last error created, and also the last error associated with a\npackage. This could either be the last error created by a sub in that package, or the last error\nwhich passed an object blessed into that package as the \"-object\" argument.\n\nError->new()\nSee the Error::Simple documentation.\n\nthrow ( [ ARGS ] )\nCreate a new \"Error\" object and throw an error, which will be caught by a surrounding \"try\"\nblock, if there is one. Otherwise it will cause the program to exit.\n\n\"throw\" may also be called on an existing error to re-throw it.\n\nwith ( [ ARGS ] )\nCreate a new \"Error\" object and returns it. This is defined for syntactic sugar, eg\n\ndie with Some::Error ( ... );\n\nrecord ( [ ARGS ] )\nCreate a new \"Error\" object and returns it. This is defined for syntactic sugar, eg\n\nrecord Some::Error ( ... )\nand return;\n\nSTATIC METHODS\nprior ( [ PACKAGE ] )\nReturn the last error created, or the last error associated with \"PACKAGE\"\n\nflush ( [ PACKAGE ] )\nFlush the last error created, or the last error associated with \"PACKAGE\".It is necessary to\nclear the error stack before exiting the package or uncaught errors generated using \"record\"\nwill be reported.\n\n$Error->flush;\n\nOBJECT METHODS\nstacktrace\nIf the variable $Error::Debug was non-zero when the error was created, then \"stacktrace\"\nreturns a string created by calling \"Carp::longmess\". If the variable was zero the\n\"stacktrace\" returns the text of the error appended with the filename and line number of\nwhere the error was created, providing the text does not end with a newline.\n\nobject\nThe object this error was associated with\n\nfile\nThe file where the constructor of this error was called from\n\nline\nThe line where the constructor of this error was called from\n\ntext\nThe text of the error\n\n$err->associate($obj)\nAssociates an error with an object to allow error propagation. I.e:\n\n$ber->encode(...) or\nreturn Error->prior($ber)->associate($ldap);\n\nOVERLOAD METHODS\nstringify\nA method that converts the object into a string. This method may simply return the same as\nthe \"text\" method, or it may append more information. For example the file name and line\nnumber.\n\nBy default this method returns the \"-text\" argument that was passed to the constructor, or\nthe string \"Died\" if none was given.\n\nvalue\nA method that will return a value that can be associated with the error. For example if an\nerror was created due to the failure of a system call, then this may return the numeric\nvalue of $! at the time.\n\nBy default this method returns the \"-value\" argument that was passed to the constructor.\n",
            "subsections": []
        },
        "PRE-DEFINED ERROR CLASSES": {
            "content": "",
            "subsections": [
                {
                    "name": "Error::Simple",
                    "content": "This class can be used to hold simple error strings and values. It's constructor takes two\narguments. The first is a text value, the second is a numeric value. These values are what will\nbe returned by the overload methods.\n\nIf the text value ends with \"at file line 1\" as $@ strings do, then this information will be\nused to set the \"-file\" and \"-line\" arguments of the error object.\n\nThis class is used internally if an eval'd block die's with an error that is a plain string.\n(Unless $Error::ObjectifyCallback is modified)\n\n$Error::ObjectifyCallback\nThis variable holds a reference to a subroutine that converts errors that are plain strings to\nobjects. It is used by Error.pm to convert textual errors to objects, and can be overridden by\nthe user.\n\nIt accepts a single argument which is a hash reference to named parameters. Currently the only\nnamed parameter passed is 'text' which is the text of the error, but others may be available in\nthe future.\n\nFor example the following code will cause Error.pm to throw objects of the class MyError::Bar by\ndefault:\n\nsub throwMyErrorBar\n{\nmy $args = shift;\nmy $err = MyError::Bar->new();\n$err->{'MyBarText'} = $args->{'text'};\nreturn $err;\n}\n\n{\nlocal $Error::ObjectifyCallback = \\&throwMyErrorBar;\n\n# Error handling here.\n}\n"
                }
            ]
        },
        "MESSAGE HANDLERS": {
            "content": "\"Error\" also provides handlers to extend the output of the \"warn()\" perl function, and to handle\nthe printing of a thrown \"Error\" that is not caught or otherwise handled. These are not\ninstalled by default, but are requested using the \":warndie\" tag in the \"use\" line.\n\nuse Error qw( :warndie );\n\nThese new error handlers are installed in $SIG{WARN} and $SIG{DIE}. If these handlers\nare already defined when the tag is imported, the old values are stored, and used during the new\ncode. Thus, to arrange for custom handling of warnings and errors, you will need to perform\nsomething like the following:\n\nBEGIN {\n$SIG{WARN} = sub {\nprint STDERR \"My special warning handler: $[0]\"\n};\n}\n\nuse Error qw( :warndie );\n\nNote that setting $SIG{WARN} after the \":warndie\" tag has been imported will overwrite the\nhandler that \"Error\" provides. If this cannot be avoided, then the tag can be explicitly\n\"import\"ed later\n\nuse Error;\n\n$SIG{WARN} = ...;\n\nimport Error qw( :warndie );\n\nEXAMPLE\nThe \"DIE\" handler turns messages such as\n\nCan't call method \"foo\" on an undefined value at examples/warndie.pl line 16.\n\ninto\n\nUnhandled perl error caught at toplevel:\n\nCan't call method \"foo\" on an undefined value\n\nThrown from: examples/warndie.pl:16\n\nFull stack trace:\n\nmain::inner('undef') called at examples/warndie.pl line 20\nmain::outer('undef') called at examples/warndie.pl line 23\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "See Exception::Class for a different module providing Object-Oriented exception handling, along\nwith a convenient syntax for declaring hierarchies for them. It doesn't provide Error's\nsyntactic sugar of \"try { ... }\", \"catch { ... }\", etc. which may be a good thing or a bad thing\nbased on what you want. (Because Error's syntactic sugar tends to break.)\n\nError::Exception aims to combine Error and Exception::Class \"with correct stringification\".\n\nTryCatch and Try::Tiny are similar in concept to Error.pm only providing a syntax that hopefully\nbreaks less.\n",
            "subsections": []
        },
        "KNOWN BUGS": {
            "content": "None, but that does not mean there are not any.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Graham Barr <gbarr@pobox.com>\n\nThe code that inspired me to write this was originally written by Peter Seibel\n<peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.\n\n\":warndie\" handlers added by Paul Evans <leonerd@leonerd.org.uk>\n",
            "subsections": []
        },
        "MAINTAINER": {
            "content": "Shlomi Fish, <http://www.shlomifish.org/> .\n",
            "subsections": []
        },
        "PAST MAINTAINERS": {
            "content": "Arun Kumar U <uarunkumar@yahoo.com>\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 1997-8 Graham Barr. All rights reserved. This program is free software; you can\nredistribute it and/or modify it under the same terms as Perl itself.\n",
            "subsections": []
        },
        "SUPPORT": {
            "content": "",
            "subsections": [
                {
                    "name": "Websites",
                    "content": "The following websites have more information about this module, and may be of help to you. As\nalways, in addition to those websites please use your favorite search engine to discover more\nresources.\n\n*   MetaCPAN\n\nA modern, open-source CPAN search engine, useful to view POD in HTML format.\n\n<https://metacpan.org/release/Error>\n\n*   Search CPAN\n\nThe default CPAN search engine, useful to view POD in HTML format.\n\n<http://search.cpan.org/dist/Error>\n\n*   RT: CPAN's Bug Tracker\n\nThe RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.\n\n<https://rt.cpan.org/Public/Dist/Display.html?Name=Error>\n\n*   CPAN Ratings\n\nThe CPAN Ratings is a website that allows community ratings and reviews of Perl modules.\n\n<http://cpanratings.perl.org/d/Error>\n\n*   CPANTS\n\nThe CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.\n\n<http://cpants.cpanauthors.org/dist/Error>\n\n*   CPAN Testers\n\nThe CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN\ndistributions.\n\n<http://www.cpantesters.org/distro/E/Error>\n\n*   CPAN Testers Matrix\n\nThe CPAN Testers Matrix is a website that provides a visual overview of the test results for\na distribution on various Perls/platforms.\n\n<http://matrix.cpantesters.org/?dist=Error>\n\n*   CPAN Testers Dependencies\n\nThe CPAN Testers Dependencies is a website that shows a chart of the test results of all\ndependencies for a distribution.\n\n<http://deps.cpantesters.org/?module=Error>\n\nBugs / Feature Requests\nPlease report any bugs or feature requests by email to \"bug-error at rt.cpan.org\", or through\nthe web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Error>. You will be\nautomatically notified of any progress on the request by the system.\n"
                },
                {
                    "name": "Source Code",
                    "content": "The code is open to the world, and available for you to hack on. Please feel free to browse it\nand play with it, or whatever. If you want to contribute patches, please send me a diff or prod\nme to pull from your repository :)\n\n<https://github.com/shlomif/perl-error.pm>\n\ngit clone git://github.com/shlomif/perl-error.pm.git\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "Shlomi Fish ( http://www.shlomifish.org/ )\n",
            "subsections": []
        },
        "BUGS": {
            "content": "Please report any bugs or feature requests on the bugtracker website\n<https://github.com/shlomif/perl-error.pm/issues>\n\nWhen submitting a bug or request, please include a test-file or a patch to an existing test-file\nthat illustrates the bug or desired feature.\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2020 by Shlomi Fish ( http://www.shlomifish.org/ ).\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Error - Error/exception handling in an OO-ish way",
    "flags": [],
    "examples": [],
    "see_also": []
}