What's broken about exceptions in Perl?

前端 未结 8 1129
孤城傲影
孤城傲影 2020-11-30 05:43

A discussion in another question got me wondering: what do other programming languages\' exception systems have that Perl\'s lacks?

Perl\'s built-in exceptions are a

相关标签:
8条回答
  • 2020-11-30 06:29

    Try::Tiny (or modules built on top of it) is the only correct way to deal with exceptions in Perl 5. The issues involved are subtle, but the linked article explains them in detail.

    Here's how to use it:

    use Try::Tiny;
    
    try {
        my $code = 'goes here';
        succeed() or die 'with an error';
    }
    catch {
        say "OH NOES, YOUR PROGRAM HAZ ERROR: $_";
    };
    

    eval and $@ are moving parts you don't need to concern yourself with.

    Some people think this is a kludge, but having read the implementations of other languages (as well as Perl 5), it's no different than any other. There is just the $@ moving part that you can get your hand caught in... but as with other pieces of machinery with exposed moving parts... if you don't touch it, it won't rip off your fingers. So use Try::Tiny and keep your typing speed up ;)

    0 讨论(0)
  • 2020-11-30 06:30

    Don't use Exceptions for regular errors. Only Fatal problems that will stop the current execution should die. All other should be handled without die.

    Example: Parameter validation of called sub: Don't die at the first problem. Check all other parameters and then decide to stop by returning something or warn and correct the faulty parameters and proceed. That do in test or development mode. But possibly die in production mode. Let the application decide this.

    JPR (my CPAN login)

    Greetings from Sögel, Germany

    0 讨论(0)
提交回复
热议问题