Perl tries to catch user-defined exceptions

I want to know if perl has a try catch mechanism similar to python where I can raise custom exceptions and handle them accordingly.

PythonCode:

   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()

I know perl is trying to catch mechnism, as shown below:

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

OR

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
  }

I focus more on if checks on catch. Is there a way to avoid checking for various errors that I catch.

+4
source share
1 answer

The closest solution is probably a direct failures object and a TryCatch for type checking.

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 {
    ...
}

custom::failures, Throwable, Exception::Class.

+5

Source: https://habr.com/ru/post/1694123/


All Articles