http://qs321.pair.com?node_id=11102465


in reply to Error codes vs die exceptions vs ...

I echo choroba's suggestion that propagating errors from nested code can be cleanly solved by throwing and catching exceptions using die and eval or tools like Try::Tiny (which wraps die/eval into a nice package). There is more to it than that though. Good exception handling can make a huge difference in cleaning up error management in code. It removes the need for most code to be aware of errors. The propagation techniques that use special sauce for returning error cases from subs require every use of the sub to manage error handling. Exception handling allows error handling in localised and easily recognised places.

Full on exception handling can use an exception object that provides as much or as little of the error context as needed from an error string or code to a full dump of the call stack! As a taste consider:

use strict; use warnings; package Error; sub new { my ($class, $errorStr, @params) = @_; my @context = caller; return bless {err => $errorStr, context => \@context, params => \@ +params}, $class; } sub Dump { my ($self) = @_; my ($package, $file, $line) = @{$self->{context}}; print "Exception: Pkg $package in file '$file' at line $line: '$se +lf->{err}'\n"; } package main; eval { DoStuff(); return 1; } or do { my $err = $@; $err->Dump() if $err->isa("Error"); }; sub DoStuff { die Error->new("Something went wrong."); }

Prints:

Exception: Pkg main in file 'delme.pl' at line 32: 'Something went wro +ng.'
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond