home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / MacPerl 4.1.3 / lib / exceptions.pl < prev    next >
Encoding:
Text File  |  1993-10-23  |  1.5 KB  |  46 lines  |  [TEXT/MPS ]

  1. or to die otherwise.
  2. # I use oddly named variables in order to make darn sure I don't conflict 
  3. # with my caller.  I also hide in my own package, and eval the code in his.
  4. # The EXCEPTION: prefix is so you can tell whether it's a user-raised
  5. # exception or a perl-raised one (eval error).
  6. # --tom
  7. #
  8. # examples:
  9. #    if (&catch('/$user_input/', 'regexp', 'syntax error') {
  10. #        warn "oops try again";
  11. #        redo;
  12. #    }
  13. #
  14. #    if ($error = &catch('&subroutine()')) { # catches anything
  15. #
  16. #    &throw('bad input') if /^$/;
  17.  
  18. sub catch {
  19.     package exception;
  20.     local($__code__, @__exceptions__) = @_;
  21.     local($__package__) = caller;
  22.     local($__exception__);
  23.  
  24.     eval "package $__package__; $__code__";
  25.     if ($__exception__ = &'thrown) {
  26.     for (@__exceptions__) {
  27.         return $__exception__ if /$__exception__/;
  28.     } 
  29.     &'throw($__exception__);
  30.     } 
  31.  
  32. sub throw {
  33.     local($exception) = @_;
  34.     die "EXCEPTION: $exception\n";
  35.  
  36. sub thrown {
  37.     $@ =~ /^(EXCEPTION: )+(.+)/ && $2;
  38.  
  39. 1;
  40.