Perl尝试捕获用户定义的异常

Che*_*tan 4 perl

我想知道perl是否有一些类似于python的try catch机制,我可以提高用户定义的异常并相应地处理.

Python代码:

   try:
       number = 6
       i_num = 3
       if i_num < number:
           raise ValueTooSmallError
       elif i_num > number:
           raise ValueTooLargeError
       break
   except ValueTooSmallError:
       print("This value is too small, try again!")
       print()
   except ValueTooLargeError:
       print("This value is too large, try again!")
       print()
Run Code Online (Sandbox Code Playgroud)

我知道perl尝试抓住机制,如下所示:

sub method_one {
    try {
        if ("number" eq "one") {
            die("one");
        } else {
            die("two");
        }
    } catch {
        if ($@ eq "one") {
            print "Failed at one";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

eval {
    open(FILE, $file) || 
      die MyFileException->new("Unable to open file - $file");
  };

  if ($@) {
    # now $@ contains the exception object of type MyFileException
    print $@->getErrorMessage();  
    # where getErrorMessage() is a method in MyFileException class
  }
Run Code Online (Sandbox Code Playgroud)

我更专注于对捕获的if检查.有没有办法可以避免检查我遇到的不同类型的错误.

dax*_*xim 5

最接近的解决方案可能是直接故障对象和TryCatch进行类型检查.

use failures qw(
    Example::Value_too_small
    Example::Value_too_large
);
use TryCatch;

try {
    my $number = 6;
    my $i_num = 3;
    if ($i_num < $number) {
        failure::Example::Value_too_small->throw({
            msg => '%d is too small, try again!',
            payload => $i_num,
        });
    } elsif ($i_num > $number) {
        failure::Example::Value_too_large->throw({
            msg => '%d is too large, try again!',
            payload => $i_num,
        });
    }
} catch (failure::Example::Value_too_small $e) {
    say sprintf $e->msg, $e->payload;
} catch (failure::Example::Value_too_large $e) {
    say sprintf $e->msg, $e->payload;
} finally {
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可以从这里升级到custom :: failures,Throwable,Exception :: Class.