The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Class::Throwable - A minimal lightweight exception class

SYNOPSIS

  use Class::Throwable;     
  
  # simple usage
  eval {
      # code code code,
      if ($something_goes_wrong) {
          throw Class::Throwable "Something has gone wrong";
      }
  };
  if ($@) {
      # we just print out the exception message here
      print "There has been an exception: " $@->getMessage();  
      # but if we are debugging we get the whole
      # stack trace as well
      if (DEBUG) {
          print $@->getStackTraceAsString();
      }
  }
  
  # it can be used to catch perl exceptions
  # and wrap them in a Class::Throwable exception
  eval {
      # generate a perl exception
      eval "2 / 0";
      # then throw our own with the 
      # perl exception as a sub-exception
      throw Class::Throwable "Throwing an exception" => $@ if $@;
  };    
  if ($@) {
      # setting the verbosity to 
      # 2 gives a full stack trace
      # including any sub-exceptions
      # (see below for examples of 
      # this output format)
      $@->toString(2);  
  }
  
  # you can also declare inline exceptions
  use Class::Throwable qw(My::App::Exception::IllegalOperation);
  
  eval {
      throw My::App::Exception::IllegalOperation "Bad, real bad";
  };

DESCRIPTION

This module implements a minimal lightweight exception object. It is meant to be a compromise between more basic solutions like Carp which can only print information and cannot handle exception objects, and more more complex solutions like Exception::Class which can be used to define complex inline exceptions and has a number of module dependencies.

METHODS

Constructor

throw ($message, $sub_exception)

The only way to construct an exception object is to throw it. This method will construct the exception object, collect all the information from the call stack and then die.

The optional $message argument can be used to pass custom information along with the exception object. Commonly this will be a string, but this module makes no attempt to enforce that it be anything other than a scalar, so more complex references or objects can be used. If no $message is passed in, a default one will be constructed for you.

The second optional argument, $sub_exception, can be used to retain information about an exception which has been caught but might not be appropriate to be re-thrown and is better wrapped within a new exception object. While this argument will commonly be another Class::Throwable object, that fact is not enforced so you can pass in normal string based perl exceptions as well.

Accessors

getMessage

This allows access to the message in the exception, to allow more granular exception reporting.

getStackTrace

This returns the raw stack trace information as an array of arrays. There are 10 values returned by caller ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) we do not bother to capture the last two as they are subject to change and meant for internal use, all others are retained in the order returned by caller.

hasSubException

The returns true (1) if this exception has a sub-exception, and false (0) otherwise.

getSubException

This allows access to the stored sub-exception.

Output Methods

This object overloads the stringification operator, and will call the toString method to perform that stringification.

toString ($verbosity)

This will print out the exception object's information at a variable level of verbosity which is specified be either the optional argument $verbosity or the value of $Class::Throwable::VERBOSE. If either value is set to 0 or below, an empty string is returned. If the value is set to 1, then the exception's message is returned. If the value is set to 2 or above, a full stack trace along with full stack traces for all sub-exceptions are returned in the format shown in stackTraceToString. This is meant to be a simple and flexible way to control the level of exception output on either a global level (with $Class::Throwable::VERBOSE) or a more granular level (with the $verbosity argument).

stringValue

This will return the normal perl stringified value of the object without going through the toString method.

stackTraceToString

This method is used to print the stack trace information, the stack trace is presented in the following format:

  >> stack frame (1)
     ----------------
     package: main
     subroutine: main::foo
     filename: my_script.pl
     line number: 12

Each subsequent stack frame will also be printed with the stack-frame number incremented for each one.

BUGS

None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it. This is based on code which has been heavily used in production sites for over 2 years now without incident.

CODE COVERAGE

I use Devel::Cover to test the code coverage of my tests, below is the Devel::Cover report on this module test suite.

 ------------------------ ------ ------ ------ ------ ------ ------ ------
 File                       stmt branch   cond    sub    pod   time  total
 ------------------------ ------ ------ ------ ------ ------ ------ ------
 Class/Throwable.pm        100.0   95.8   66.7  100.0  100.0  100.0   96.7
 ------------------------ ------ ------ ------ ------ ------ ------ ------
 Total                     100.0   95.8   66.7  100.0  100.0  100.0   96.7
 ------------------------ ------ ------ ------ ------ ------ ------ ------

SEE ALSO

There are a number of ways to do exceptions with perl, I was not really satisifed with the way anyone else did them, so I created this module. However, if you find this module unsatisfactory, you may want to check these out.

Exception::Class

This in one of the more common exception classes out there. It does an excellent job with it's default behavior, and allows a number of complex options which can likely serve any needs you might have. My reasoning for not using this module is that I felt these extra options made things more complex than they needed to be, it also introduced a number of dependencies. I am not saying this module is bloated at all, but that for me it was far more than I have found I needed. If you have heavy duty exception needs, this is your module.

Error

This is the classic perl exception module, complete with a try/catch mechanism. This module has a lot of bad karma associated with it because of the obscure nested closure memory leak that try/catch has. I never really liked the way its exception object Error::Simple did things either.

Exception

This module I have never really experimented with, so take my opinion with a large grain of salt. My problem with this module was always that it seemed to want to do too much. It attempts to make perl into a language with real exceptions, but messing with %SIG handlers and other such things. This can be dangerous territory sometimes, and for me, far more than my needs.

AUTHOR

stevan little, <stevan@iinteractive.com>

COPYRIGHT AND LICENSE

Copyright 2004 by Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.