{
    "mode": "perldoc",
    "parameter": "Exception::Class",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Exception%3A%3AClass/json",
    "generated": "2026-06-10T05:01:13Z",
    "synopsis": "use Exception::Class (\n'MyException',\n'AnotherException' => { isa => 'MyException' },\n'YetAnotherException' => {\nisa         => 'AnotherException',\ndescription => 'These exceptions are related to IPC'\n},\n'ExceptionWithFields' => {\nisa    => 'YetAnotherException',\nfields => [ 'grandiosity', 'quixotic' ],\nalias  => 'throwfields',\n},\n);\nuse Scalar::Util qw( blessed );\nuse Try::Tiny;\ntry {\nMyException->throw( error => 'I feel funny.' );\n}\ncatch {\ndie $ unless blessed $ && $->can('rethrow');\nif ( $->isa('Exception::Class') ) {\nwarn $->error, \"\\n\", $->trace->asstring, \"\\n\";\nwarn join ' ', $->euid, $->egid, $->uid, $->gid, $->pid, $->time;\nexit;\n}\nelsif ( $->isa('ExceptionWithFields') ) {\nif ( $->quixotic ) {\nhandlequixoticexception();\n}\nelse {\nhandlenonquixoticexception();\n}\n}\nelse {\n$->rethrow;\n}\n};\n# without Try::Tiny\neval { ... };\nif ( my $e = Exception::Class->caught ) { ... }\n# use an alias - without parens subroutine name is checked at\n# compile time\nthrowfields error => \"No strawberry\", grandiosity => \"quite a bit\";",
    "sections": {
        "NAME": {
            "content": "Exception::Class - A module that allows you to declare real exception classes in Perl\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 1.45\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Exception::Class (\n'MyException',\n\n'AnotherException' => { isa => 'MyException' },\n\n'YetAnotherException' => {\nisa         => 'AnotherException',\ndescription => 'These exceptions are related to IPC'\n},\n\n'ExceptionWithFields' => {\nisa    => 'YetAnotherException',\nfields => [ 'grandiosity', 'quixotic' ],\nalias  => 'throwfields',\n},\n);\nuse Scalar::Util qw( blessed );\nuse Try::Tiny;\n\ntry {\nMyException->throw( error => 'I feel funny.' );\n}\ncatch {\ndie $ unless blessed $ && $->can('rethrow');\n\nif ( $->isa('Exception::Class') ) {\nwarn $->error, \"\\n\", $->trace->asstring, \"\\n\";\nwarn join ' ', $->euid, $->egid, $->uid, $->gid, $->pid, $->time;\n\nexit;\n}\nelsif ( $->isa('ExceptionWithFields') ) {\nif ( $->quixotic ) {\nhandlequixoticexception();\n}\nelse {\nhandlenonquixoticexception();\n}\n}\nelse {\n$->rethrow;\n}\n};\n\n# without Try::Tiny\neval { ... };\nif ( my $e = Exception::Class->caught ) { ... }\n\n# use an alias - without parens subroutine name is checked at\n# compile time\nthrowfields error => \"No strawberry\", grandiosity => \"quite a bit\";\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "RECOMMENDATION 1: If you are writing modern Perl code with Moose or Moo I highly recommend using\nThrowable instead of this module.\n\nRECOMMENDATION 2: Whether or not you use Throwable, you should use Try::Tiny.\n\nException::Class allows you to declare exception hierarchies in your modules in a \"Java-esque\"\nmanner.\n\nIt features a simple interface allowing programmers to 'declare' exception classes at compile\ntime. It also has a base exception class, Exception::Class::Base, that can be easily extended.\n\nIt is designed to make structured exception handling simpler and better by encouraging people to\nuse hierarchies of exceptions in their applications, as opposed to a single catch-all exception\nclass.\n\nThis module does not implement any try/catch syntax. Please see the \"OTHER EXCEPTION MODULES\n(try/catch syntax)\" section for more information on how to get this syntax.\n\nYou will also want to look at the documentation for Exception::Class::Base, which is the default\nbase class for all exception objects created by this module.\n",
            "subsections": []
        },
        "DECLARING EXCEPTION CLASSES": {
            "content": "Importing \"Exception::Class\" allows you to automagically create Exception::Class::Base\nsubclasses. You can also create subclasses via the traditional means of defining your own\nsubclass with @ISA. These two methods may be easily combined, so that you could subclass an\nexception class defined via the automagic import, if you desired this.\n\nThe syntax for the magic declarations is as follows:\n\n'MANDATORY CLASS NAME' => \\%optionalhashref\n\nThe hashref may contain the following options:\n\n*   isa\n\nThis is the class's parent class. If this isn't provided then the class name in\n$Exception::Class::BASEEXCCLASS is assumed to be the parent (see below).\n\nThis parameter lets you create arbitrarily deep class hierarchies. This can be any other\nException::Class::Base subclass in your declaration *or* a subclass loaded from a module.\n\nTo change the default exception class you will need to change the value of\n$Exception::Class::BASEEXCCLASS *before* calling \"import\". To do this simply do something\nlike this:\n\nBEGIN { $Exception::Class::BASEEXCCLASS = 'SomeExceptionClass'; }\n\nIf anyone can come up with a more elegant way to do this please let me know.\n\nCAVEAT: If you want to automagically subclass an Exception::Class::Base subclass loaded from\na file, then you *must* compile the class (via use or require or some other magic) *before*\nyou import \"Exception::Class\" or you'll get a compile time error.\n\n*   fields\n\nThis allows you to define additional attributes for your exception class. Any field you\ndefine can be passed to the \"throw\" or \"new\" methods as additional parameters for the\nconstructor. In addition, your exception object will have an accessor method for the fields\nyou define.\n\nThis parameter can be either a scalar (for a single field) or an array reference if you need\nto define multiple fields.\n\nEach field name must be a legal Perl identifier: it starts with a ASCII letter or\nunderscore, and is followed by zero or more ASCII letters, ASCII digits, or underscores. If\na field name does not match this, the creation of that exception class croaks.\n\nFields will be inherited by subclasses.\n\n*   alias\n\nSpecifying an alias causes this class to create a subroutine of the specified name in the\n*caller's* namespace. Calling this subroutine is equivalent to calling \"<class>->throw(@)\"\nfor the given exception class.\n\nBesides convenience, using aliases also allows for additional compile time checking. If the\nalias is called *without parentheses*, as in \"throwfields \"an error occurred\"\", then Perl\nchecks for the existence of the \"throwfields\" subroutine at compile time. If instead you do\n\"ExceptionWithFields->throw(...)\", then Perl checks the class name at runtime, meaning that\ntypos may sneak through.\n\n*   description\n\nEach exception class has a description method that returns a fixed string. This should\ndescribe the exception *class* (as opposed to any particular exception object). This may be\nuseful for debugging if you start catching exceptions you weren't expecting (particularly if\nsomeone forgot to document them) and you don't understand the error messages.\n\nThe \"Exception::Class\" magic attempts to detect circular class hierarchies and will die if it\nfinds one. It also detects missing links in a chain, for example if you declare Bar to be a\nsubclass of Foo and never declare Foo.\n",
            "subsections": []
        },
        "Try::Tiny": {
            "content": "If you are interested in adding try/catch/finally syntactic sugar to your code then I recommend\nyou check out Try::Tiny. This is a great module that helps you ignore some of the weirdness with\n\"eval\" and $@. Here's an example of how the two modules work together:\n\nuse Exception::Class ( 'My::Exception' );\nuse Scalar::Util qw( blessed );\nuse Try::Tiny;\n\ntry {\nmightthrow();\n}\ncatch {\nif ( blessed $ && $->isa('My::Exception') ) {\nhandleit();\n}\nelse {\ndie $;\n}\n};\n\nNote that you cannot use \"Exception::Class->caught\" with Try::Tiny.\n",
            "subsections": []
        },
        "Catching Exceptions Without Try::Tiny": {
            "content": "\"Exception::Class\" provides some syntactic sugar for catching exceptions in a safe manner:\n\neval {...};\n\nif ( my $e = Exception::Class->caught('My::Error') ) {\ncleanup();\ndosomethingwithexception($e);\n}\n\nThe \"caught\" method takes a class name and returns an exception object if the last thrown\nexception is of the given class, or a subclass of that class. If it is not given any arguments,\nit simply returns $@.\n\nYou should always make a copy of the exception object, rather than using $@ directly. This is\nnecessary because if your \"cleanup\" function uses \"eval\", or calls something which uses it, then\n$@ is overwritten. Copying the exception preserves it for the call to\n\"dosomethingwithexception\".\n\nException objects also provide a caught method so you can write:\n\nif ( my $e = My::Error->caught ) {\ncleanup();\ndosomethingwithexception($e);\n}\n",
            "subsections": [
                {
                    "name": "Uncatchable Exceptions",
                    "content": "Internally, the \"caught\" method will call \"isa\" on the exception object. You could make an\nexception \"uncatchable\" by overriding \"isa\" in that class like this:\n\npackage Exception::Uncatchable;\n\nsub isa { shift->rethrow }\n\nOf course, this only works if you always call \"Exception::Class->caught\" after an \"eval\".\n"
                }
            ]
        },
        "USAGE RECOMMENDATION": {
            "content": "If you're creating a complex system that throws lots of different types of exceptions, consider\nputting all the exception declarations in one place. For an app called Foo you might make a\n\"Foo::Exceptions\" module and use that in all your code. This module could just contain the code\nto make \"Exception::Class\" do its automagic class creation. Doing this allows you to more easily\nsee what exceptions you have, and makes it easier to keep track of them.\n\nThis might look something like this:\n\npackage Foo::Bar::Exceptions;\n\nuse Exception::Class (\nFoo::Bar::Exception::Senses =>\n{ description => 'sense-related exception' },\n\nFoo::Bar::Exception::Smell => {\nisa         => 'Foo::Bar::Exception::Senses',\nfields      => 'odor',\ndescription => 'stinky!'\n},\n\nFoo::Bar::Exception::Taste => {\nisa         => 'Foo::Bar::Exception::Senses',\nfields      => [ 'taste', 'bitterness' ],\ndescription => 'like, gag me with a spoon!'\n},\n\n...\n);\n\nYou may want to create a real module to subclass Exception::Class::Base as well, particularly if\nyou want your exceptions to have more methods.\n",
            "subsections": [
                {
                    "name": "Subclassing Exception::Class::Base",
                    "content": "As part of your usage of \"Exception::Class\", you may want to create your own base exception\nclass which subclasses Exception::Class::Base. You should feel free to subclass any of the\nmethods documented above. For example, you may want to subclass \"new\" to add additional\ninformation to your exception objects.\n"
                }
            ]
        },
        "Exception::Class FUNCTIONS": {
            "content": "The \"Exception::Class\" method offers one function, \"Classes\", which is not exported. This method\nreturns a list of the classes that have been created by calling the \"Exception::Class\" \"import\"\nmethod. Note that this is *all* the subclasses that have been created, so it may include\nsubclasses created by things like CPAN modules, etc. Also note that if you simply define a\nsubclass via the normal Perl method of setting @ISA or \"use base\", then your subclass will not\nbe included.\n",
            "subsections": []
        },
        "SUPPORT": {
            "content": "Bugs may be submitted at <https://github.com/houseabsolute/Exception-Class/issues>.\n\nI am also usually active on IRC as 'autarch' on \"irc://irc.perl.org\".\n",
            "subsections": []
        },
        "SOURCE": {
            "content": "The source code repository for Exception-Class can be found at\n<https://github.com/houseabsolute/Exception-Class>.\n",
            "subsections": []
        },
        "DONATIONS": {
            "content": "If you'd like to thank me for the work I've done on this module, please consider making a\n\"donation\" to me via PayPal. I spend a lot of free time creating free software, and would\nappreciate any support you'd care to offer.\n\nPlease note that I am not suggesting that you must do this in order for me to continue working\non this particular software. I will continue to do so, inasmuch as I have in the past, for as\nlong as it interests me.\n\nSimilarly, a donation made in this way will probably not make me work on this software much\nmore, unless I get so many donations that I can consider working on free software full time\n(let's all have a chuckle at that together).\n\nTo donate, log into PayPal and send money to autarch@urth.org, or use the button at\n<https://www.urth.org/fs-donation.html>.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Dave Rolsky <autarch@urth.org>\n",
            "subsections": []
        },
        "CONTRIBUTORS": {
            "content": "*   Alexander Batyrshin <0x62ash@gmail.com>\n\n*   brian d foy <brian.d.foy@gmail.com>\n\n*   Leon Timmermans <fawaka@gmail.com>\n\n*   Ricardo Signes <rjbs@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2021 by Dave Rolsky.\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\nThe full text of the license can be found in the LICENSE file included with this distribution.\n",
            "subsections": []
        }
    },
    "summary": "Exception::Class - A module that allows you to declare real exception classes in Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}