我有一个名为"SamplePkg"的包。我有另一个脚本使用SamplePkg,创建一个对象并调用一个方法。
package SamplePkg;
use strict;
use DBI;
use Try::Tiny;
my $dbh = DBI_>connect(..., { RaiseError => 1 });
sub new {
my $self = {};
$self->{CODE} = 0;
bless($self);
return $self;
}
sub do_something {
my $self = shift;
try {
my $query = "select myvalue from mytable";
$sth = $dbh->prepare($query);
$sth->execute();
} catch { $self->{CODE} = 100; return; }
$self->{CODE} = 50;
}
The other script
use SamplePkg;
my $object = SamplePkg->new();
$object->do_something();
print "Code is: $object->{CODE}n";
Questions:
- For some reason, the try block doesn't catch the DB error (myvalue is not a valid column name)
- The "return" in the catch block does not return to the calling script
- The output gives the error code as 50
try { ... } catch { ... };
是
try(sub { ... }, catch(sub { ... }));
从捕获异常时调用的子进程返回,而不是从try
所在的子进程返回。
你可以用
try {
my $query = "select myvalue from mytable";
$sth = $dbh->prepare($query);
$sth->execute();
$self->{CODE} = 50;
} catch {
$self->{CODE} = 100;
};
或者你需要更像
my $success = try {
my $query = "select myvalue from mytable";
$sth = $dbh->prepare($query);
$sth->execute();
return 1;
} catch {
return 0;
};
... do stuff ...
$self->{CODE} = $succes ? 50 : 100;