eval and exception

corliss at alaskapm.org corliss at alaskapm.org
Tue May 1 18:08:53 CDT 2001


On Tue, 1 May 2001, R. J. wrote:

> Howdy,
> 
> I have a question regarding capturing exception in
> eval. I could not use eval to catch the exception. 
> For instance, I wrote a simple program in prac.pl as
> ($a, $b) = (10, 0);
> print $a / $b;
> Then in main.pl, I wrote
> eval {
>   system("perl -w main.pl");
> };
> if ($@) {
>   print "error";
> }
> It just didn't print out "error" as I expected, which
> means it didn't send any fatal string parameter to $@,
> then I added
> or die after system command, it's still the same. Is
> it because I am using system command, so the process
> is different. 

Here's a one-liner that works:

perl -e '$a = 10; $b = 0; eval { print $10 / $b; }; print "Result: $@\n"'

The issue here is that what is that the system function doesn't work that
way--all it returns is the return value of the shelled command, nothing more.
All output of system, whether it be to STDOUT or STDERR, goes straight to your
program's channels.

Also note that if you're going to do what I did above, what's listed in the
eval must be able to be compiled, which is why substituting a simple 
'print 10 / 0' won't work in the eval.

> Now that I just call a perl program in the eval, what
> if I run a c program or others with system command,
> will eval be able to catch the exception?

Once again, system won't catch exceptions, per se, it just returns the exit
status.

	--Arthur Corliss
	  Perl Monger/Alaska Perl Mongers
	  http://www.alaskapm.org/

=================================================
Mailing list info:  If at any time you wish to (un|re)subscribe to
the list send the request to majordomo at hfb.pm.org.  All requests
should be in the body, and look like such
                  subscribe anchorage-pm-list
                  unsubscribe anchorage-pm-list



More information about the Anchorage-pm mailing list