Try Catch with Assert Statement

B

Bpejman

Hi Everyone,

Can someone please shed some light on this Try and Catch issue that
I'm running into? I would highly appreciate any help and/or
guidance. I've researched the web thoroughly and still no luck. I
need to know exactly what libs I need to import into my program to be
able to do the below statement (as done similarly in Python).

sub foo {
try {
assert (0);

} catch {
print "Caught assertion error\n";
};
}

Now, I've used all of the below libraries but unfortunately
"assert(0);" does not jump into the catch {} scope. It simply exists
the program from there where in other languages, assert always raises
an exception which is caught by except{} or catch{} statement.

use Carp::Assert;
use Test::Harness::Assert;
use Error;

I do not want to use Eval and if ($@) since I cannot return any values
from within Eval. For example, the following will not work for me:

print foo(); #does not print any of the return codes from function
foo since they reside within the eval.

sub foo {
eval {
assert (1);
return 1;
};
if ($@) {
print "oops";
return 0;
}
}

Thanks everyone!!!
Bobby
 
A

Ala Qumsieh

I do not want to use Eval and if ($@) since I cannot return any values
from within Eval. For example, the following will not work for me:

Yes you can. From 'perldoc -f eval':

In both forms, the value returned is the value of the last
expression evaluated inside the mini-program; a return state-
ment may be also used, just as with subroutines. The expres-
sion providing the return value is evaluated in void, scalar,
or list context, depending on the context of the eval itself.

print foo(); #does not print any of the return codes from function
foo since they reside within the eval.

The return value of foo() is different from the return value of your eval
block. You'll need to save the return value of your eval, and make it the
return value of your sub. Something like this:
sub foo {
eval {

my $evalReturn = eval {
assert (1);
return 1;
};
if ($@) {
print "oops";
return 0;
}

return $evalReturn;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top