in reply to Re^5: STDERR in Test Results
in thread STDERR in Test Results

To throw errors, call die. To throw warnings, call warn

The next version of the module will call warn so I can trap the output with Test::Warn

However, I will not call die. I find it frustrating when modules die. Especially modules where there is a reasonable chance that there may be an error such as when they are dealing with a network or rely on the user to provide input in a particular format such as valid JSON - I attempt not to inflict that frustration on others.

Replies are listed 'Best First'.
Re^7: STDERR in Test Results
by afoken (Chancellor) on Jun 27, 2023 at 21:14 UTC
    However, I will not call die. I find it frustrating when modules die.

    WTF?

    Especially modules where there is a reasonable chance that there may be an error such as when they are dealing with a network or rely on the user to provide input in a particular format such as valid JSON

    So, what should your module do when being fed with garbage instead of sane input? Pretend nothing evil has happened? Invent other, sane input? Ask for more garbage to be stuffed into your module?

    What should it do if the network goes down or a required service somewhere on the internet can't be reached? Wait for the heat death of the universe?

    What should it do if the system runs out of disk space? Gain root privileges and recursively delete all files not used in the last three years?

    I attempt not to inflict that frustration on others.

    Get over it. There is nothing to be frustrated about if an exception occurs (i.e. die is called). It is completely normal, it is "just" another way of control flow.

    The butt-ugly alternative "solution" is to return some kind of error information in-band and check each and every function call result for error information. In other words, C:

    /tmp>cat error.c #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char ** argv) { int fd; char buf[100]; ssize_t n; fd = open("foo", O_RDONLY); if (fd == -1) { perror("failed to open foo"); /* evaluates errno */ return 1; } n = read(fd, buf, sizeof(buf)); if (n == -1) { perror("failed to read from foo"); return 2; } if (n != sizeof(buf)) { fprintf(stderr, "Short read from foo (got %z, expected + %z)\n", n, sizeof(buf)); return 3; } if (close(fd) == -1) { perror("failed to close foo"); return 4; } // and so on ... } /tmp>make error cc error.c -o error /tmp>./error failed to open foo: No such file or directory /tmp>

    Update: Yes, you could implement a kind of exception handling in C using setjmp/sigsetjmp and longjmp/siglongjmp. Be prepared for "interesting" results due to undefined behaviour ...

    The smart way is to accept that things can go wrong:

    try { line = console.readLine(); if (line.length() == 0) { throw new EmptyLineException("The line read from console was e +mpty!"); } console.printLine("Hello %s!" % line); } catch (EmptyLineException e) { console.printLine("Hello!"); } catch (Exception e) { console.printLine("Error: " + e.message()); } else { console.printLine("The program ran successfully."); } finally { console.printLine("The program is now terminating."); }

    (Pseudocode-example stolen from Exception handling.)

    This can be very useful e.g. if you need to work with a database:

    Transactions

    Transactions are a fundamental part of any robust database system. They protect against errors and database corruption by ensuring that sets of related changes to the database take place in atomic (indivisible, all-or-nothing) units.

    [...]

    The recommended way to implement robust transactions in Perl applications is to enable "RaiseError" and catch the error that's 'thrown' as an exception. For example, using Try::Tiny:

    use Try::Tiny; $dbh->{AutoCommit} = 0; # enable transactions, if possible $dbh->{RaiseError} = 1; try { foo(...) # do lots of work here bar(...) # including inserts baz(...) # and updates $dbh->commit; # commit the changes if we get this far } catch { warn "Transaction aborted because $_"; # Try::Tiny copies $@ into +$_ # now rollback to undo the incomplete changes # but do it in an eval{} as it may also fail eval { $dbh->rollback }; # add other application on-error-clean-up code here };

    If the RaiseError attribute is not set, then DBI calls would need to be manually checked for errors, typically like this:

    $h->method(@args) or die $h->errstr;

    With RaiseError set, the DBI will automatically die if any DBI method call on that handle (or a child handle) fails, so you don't have to test the return value of each method call. [...]

    A major advantage of the eval approach is that the transaction will be properly rolled back if any code (not just DBI calls) in the inner application dies for any reason. The major advantage of using the $h->{RaiseError} attribute is that all DBI calls will be checked automatically. Both techniques are strongly recommended.

    (Ripped right out of the DBI documentation.)

    Update: Compare with "Exceptions" in Image::Magick: You have to check each and every return value, and you need to do that in at least three different ways, depending on what the function is expected to return. There is NO exception handing in Image::Magick.

    The main point is that if you accidentally forget to check for errors, your programm will die. It won't chew on garbage that happens to linger around somewhere in memory and it won't produce any more garbage. It will just stop and exit with an error message. In C, omitting error checks will cause a lot of "interesting" results instead.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

      I don't like dieing at any point in my programs and I look down on code which does that and forces me to try/catch/eval each of its calls instead of checking the error code that each function, IMO, should return (with reasonable exceptions of course).

      I avoided to express my opinions as I respect the particular opinion of those particular Monks who were in favour of die as error signaling and decided to keep quiet and contemplate on their points and see if I can change my opinion.

      Well, I haven't mainly because of reasons of style. I still return error codes or error hashes with code+message. I started with C, and it shows, and I think I will die with C.

      But! I found a compromise: I now consider a die to be an exception (as in, e.g. C++/Java) and it does not look as the "nutter's nuclear option" as it did. And I may even experiment dieing with an Exception object (read on before telling me that that's possible already :)):

      use Storable; use MIME::Base64; use Data::Dumper; eval { die encode_base64(freeze({errorcode => 12, errormess => 'you have die +d'})); }; print "error caught: ".Dumper(thaw(decode_base64($@))) if $@;

      But at that exact point of my epiphany I learned that die can throw ANYTHING (about time!), so:

      use Data::Dumper; eval { die {errorcode => 12, errormess => 'you have died'}; }; print "error caught: ".Dumper($@) if $@; # or even better eval { die bless {errorcode => 12, errormess => 'you have died'} => 'My::Exc +eption'; }; print "error caught2: ".$@->{errormess}."\n" if $@ and ref($@) eq 'My: +:Exception';

      So, yes, I can view die as an exception and am prepared not to consider it antisocial, from now on. The only problem remaining is performance:

      use Storable qw/freeze thaw/; use MIME::Base64; use Data::Dumper; use Benchmark qw/:all/; use strict; use warnings; sub die_bliako_way { die encode_base64(freeze({errorcode => 12, errormsg => 'you have die +d'})); } sub die_common_sense { die {errorcode => 12, errormsg => 'you have died'}; } sub die_common_sense_blessed { die bless {errorcode => 12, errormsg => 'you have died'} => 'My::Exc +eption'; } sub no_die { return {errorcode => 12, errormsg => 'you have died'}; } timethese(10_000_000, { 'die_bliako_way' => sub { eval { die_bliako_way }; if( $@ && exists(thaw(decode_base64($@))->{errorcode}) ){ } }, 'die_common_sense' => sub { eval { die_common_sense }; if( $@ && exists($@->{errorcode}) ){ } }, 'no_die' => sub { my $ret = no_die(); if( exists $ret->{errorcode} ){ } } });
      Benchmark: timing 10000000 iterations of die_bliako_way, die_common_se +nse, die_common_sense_blessed, no_die... die_bliako_way: 56 wallclock secs (55.04 usr + 0.01 sys = 55.05 CPU) +@ 181653.04/s (n=10000000) die_common_sense: 5 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU +) @ 1904761.90/s (n=10000000) die_common_sense_blessed: 5 wallclock secs ( 5.36 usr + 0.00 sys = +5.36 CPU) @ 1865671.64/s (n=10000000) no_die: 5 wallclock secs ( 3.77 usr + 0.00 sys = 3.77 CPU) @ 26 +52519.89/s (n=10000000)

      No contest there for no_die. But the test may be misleading because no_die() needs constant return status checking with an if exists. Whereas, as you show in the transactions example you provided, functions which die can skipp the individual checking and enclose them all in one big try{}catch{} block. Which is probably way faster. And I don't know which looks uglier: huge try{}catch{} blocks or endless if func() then else (actually I think the latter).

      So, thanks for the food for thought you provided. I am much more inclined in using die now in subs especially the dieing with custom-made exception objects.

      bw, bliako

Re^7: STDERR in Test Results
by stevieb (Canon) on Jun 28, 2023 at 02:53 UTC
    However, I will not call die.

    I agree with afoken's "WTF" here.

    There are many instances where it would be dangerous to NOT throw an exception. For example... my webapp that front-ends a connection to Tesla's API... you hammer that too hard without a proper auth token and I don't throw, that may cause issues. I'm not going to nicely keep telling you to please don't do that, I'm breaking your caller.

    Another example is my IPC::Shareable software. If you try to write to a memory location that isn't yours, you should know better, and I'm throwing an exception.

    The case that's relative here is the test software. Your tests should use a liberal amount of throws_ok() or similar to ensure that you catch as many possible exception cases as your software throws.

    Here's an example use of throws_ok():

    use Test::Exception; throws_ok { 0/0 } qr/Illegal division by zero/, "whatever_sub() throws if trying to divide by zero ok";

    You can do it without Test::Exception with a bit more work:

    my $div_by_zero_ok = eval { 0 / 0; 1; }; is $div_by_zero_ok, undef, "whatever_sub() barfs properly if dividing by zero ok";