archon has asked for the wisdom of the Perl Monks concerning the following question:

I'm using CGI::Application. The way it works is a form parameter sets a particular mode. In this mode, a subroutine is called and that subroutine returns an HTML::Template->output which produces the page.

So in one mode I have a method that calls another subroutine which returns two list references. It is possible for this subroutine to come across an error and produce an error message. If it does get an error, I would like the calling method to return an error page HTML::Template with the error message. Otherwise, I would like it to take the two list refs and go about its business.

My question, then, is what is the proper way to go about doing this? I tried (heh) using and throwing an exception in the subroutine, but I can't return() from the try block. I could return the error string instead from the subroutine and then have the method figure out if something went wrong using ref(), but that feels dirty to me.


Replies are listed 'Best First'.
Re: error handling
by Zaxo (Archbishop) on Jun 28, 2003 at 02:57 UTC

    You're describing a typical try ... catch situation. Have the error die with the message, call with eval {}, and check $@ after eval returns.

    After Compline,

      i must have been overanalyzing the problem from the start. i don't know why i didn't think of that.

      i did attempt the try...catch thing with but it stopped me from doing a return within the block.

        This is the mechanism used by under the hood, more or less. While is a much prettier interface than checking $@ yourself, it has some drawbacks. Since the arguments to both try and catch are anonymous subs, return will return from those and not from the enclosing sub, as you've experienced. You'll have to set up a variable with the value you want to return and then do so outside of try/catch.