Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl包错误处理问题_Perl_Exception_Try Catch_Package - Fatal编程技术网

Perl包错误处理问题

Perl包错误处理问题,perl,exception,try-catch,package,Perl,Exception,Try Catch,Package,我有一个叫做“SamplePkg”的包。我还有另一个脚本,它使用SamplePkg,创建一个对象并调用一个方法 包装样品包装; 严格使用; 使用DBI; 使用Try::Tiny my$dbh=DBI\u>connect(…,{RaiseError=>1}) 次新{ 我的$self={}; $self->{CODE}=0; 祝福(自我); 返回$self; } 做点什么{ 我的$self=shift; 试试{ my$query=“从mytable中选择myvalue”; $sth=$dbh->p

我有一个叫做“SamplePkg”的包。我还有另一个脚本,它使用SamplePkg,创建一个对象并调用一个方法


包装样品包装;
严格使用;
使用DBI;
使用Try::Tiny

my$dbh=DBI\u>connect(…,{RaiseError=>1})

次新{ 我的$self={}; $self->{CODE}=0; 祝福(自我); 返回$self; }

做点什么{ 我的$self=shift; 试试{ my$query=“从mytable中选择myvalue”; $sth=$dbh->prepare($query); $sth->execute(); }catch{$self->{CODE}=100;return;}

$self->{CODE}=50; }

另一个脚本


使用SamplePkg

my$object=SamplePkg->new(); $object->do_something()

打印“代码为:$object->{Code}\n”;

问题:

  • 由于某些原因,try块没有捕获DB错误(myvalue不是有效的列名)
  • catch块中的“return”不会返回到调用脚本
  • 输出给出的错误代码为50
真是

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;
真是

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;