in reply to Re: Exiting script from subs
in thread Exiting script from subs

Question, as it has come up in this thread twice, and that is the issue of die() vs exit((). The Camel states that one should not exit a subroutine when an error needs to be trapped. But if not, is die necessary, or is exit sufficient?

Comments?


—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re^3: Exiting script from subs
by dragonchild (Archbishop) on Apr 15, 2005 at 13:12 UTC
    What the Camel does or doesn't say is mostly irrelevant. If your coding standards allow for exit() within a subroutine, then use it. However, most of the community has come to expect die() within subroutines and exit() (if it's even used) from the main scope.

    Now, die() and exit() do different things. The biggest difference is

    eval { print "Inside\n"; die; }; print "Outside\n"; ---- Inside Outside
    vs.
    eval { print "Inside\n"; exit; }; print "Outside\n"; ---- Inside
    exit() exits, end of story. die() allows for some manner of error trapping. This is the main reason why die() is preferred within subroutines. You may want to reuse that subroutine somewhere else that wants to be able to trap the abnormal termination. Also, die() triggers $SIG{DIE}, which can also be useful to trap.
      You can trap an exit (termination of a script) as well.
      END { print "Outside"; } eval { print "Inside\n"; exit; }; print "Outside\n"; ---- Inside Outside
      -- gam3
      A picture is worth a thousand words, but takes 200K.
        That's not trapping an exit. That's trapping the termination of the script. Remove your eval and change your exit to a die and see what happens.
Re^3: Exiting script from subs
by gellyfish (Monsignor) on Apr 15, 2005 at 13:10 UTC

    I would say not, for one thing it limits the possibility of reuse in your code if you are to issue the untrappable exit() in your subroutine.

    /J\