Is Try::Tiny still recommended for exception handling in Perl 5.14 or later?

前端 未结 6 1899
迷失自我
迷失自我 2020-12-07 12:11

The consensus of the Perl community seems to be that Try::Tiny is the preferred way to handle exceptions.

Perl 5.14 (which is the version I use) seems to solve the

6条回答
  •  不思量自难忘°
    2020-12-07 12:40

    It was always a case of personal preference. Do you prefer

    my $rv;
    if (!eval { $rv = f(); 1 } ) {
       ...
    }
    

    or

    my $rv = try {
       f();
    } catch {
       ...
    };
    

    But keep in mind the latter uses anon subs, so it messes with return, as well as next and the like. Try::Tiny's try-catch might well end up far more complicated as you add communication channels between the catch block and outside of it.

    The best case (simplest) scenario for returning on exception is if $rv is always true when there is no exception. It would look like the following:

    my $rv;
    if ($rv = eval { f() }) {
       ...
       return;
    }
    

    vs

    my $rv = try {
       f();
    } catch {
       ...
    };
    
    if (!$rv) {
       return;
    }
    

    That's why I would use TryCatch instead of Try::Tiny were I to use such a module.

    The change to Perl simply means that you can do if ($@) again. In other words,

    my $rv;
    if (!eval { $rv = f(); 1 } ) {
       ...
    }
    

    can be written

    my $rv = eval { f() };
    if ($@) {
       ...
    }
    

提交回复
热议问题