This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #71710] fixes for File::Find
[perl5.git] / lib / exceptions.pl
1 warn "Legacy library @{[(caller(0))[6]]} will be removed from the Perl core distribution in the next major release. Please install it from the CPAN distribution Perl4::CoreLibs. It is being used at @{[(caller)[1]]}, line @{[(caller)[2]]}.\n";
2
3 # exceptions.pl
4 # tchrist@convex.com
5 #
6 # This library is no longer being maintained, and is included for backward
7 # compatibility with Perl 4 programs which may require it.
8 # This legacy library is deprecated and will be removed in a future
9 # release of perl.
10 #
11 # In particular, this should not be used as an example of modern Perl
12 # programming techniques.
13
14 # Here's a little code I use for exception handling.  It's really just
15 # glorfied eval/die.  The way to use use it is when you might otherwise
16 # exit, use &throw to raise an exception.  The first enclosing &catch
17 # handler looks at the exception and decides whether it can catch this kind
18 # (catch takes a list of regexps to catch), and if so, it returns the one it
19 # caught.  If it *can't* catch it, then it will reraise the exception
20 # for someone else to possibly see, or to die otherwise.
21
22 # I use oddly named variables in order to make darn sure I don't conflict 
23 # with my caller.  I also hide in my own package, and eval the code in his.
24
25 # The EXCEPTION: prefix is so you can tell whether it's a user-raised
26 # exception or a perl-raised one (eval error).
27
28 # --tom
29 #
30 # examples:
31 #       if (&catch('/$user_input/', 'regexp', 'syntax error') {
32 #               warn "oops try again";
33 #               redo;
34 #       }
35 #
36 #       if ($error = &catch('&subroutine()')) { # catches anything
37 #
38 #       &throw('bad input') if /^$/;
39
40 sub catch {
41     package exception;
42     local($__code__, @__exceptions__) = @_;
43     local($__package__) = caller;
44     local($__exception__);
45
46     eval "package $__package__; $__code__";
47     if ($__exception__ = &'thrown) {
48         for (@__exceptions__) {
49             return $__exception__ if /$__exception__/;
50         } 
51         &'throw($__exception__);
52     } 
53
54
55 sub throw {
56     local($exception) = @_;
57     die "EXCEPTION: $exception\n";
58
59
60 sub thrown {
61     $@ =~ /^(EXCEPTION: )+(.+)/ && $2;
62
63
64 1;