Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Exception handling and "trap" vs. TRAPNAL()



    Hi Bart :)

 * Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> dixit:
> : I want to replace this code:
> : 
> :     command1 && {# handle here some possible error probably exiting}
> :     command2 && {# handle here exactly the same error as before}
> :     ...
> :     commandn && {# incredible, here we must handle a similar error}
> : 
> :     with this one:
> : 
> :     trap 'throw commonerror$LINENO' ZERR
> :     {
> :         command1
> :         command2
> :         command3
> :     } always {
> :         # Here we catch and handle the common error
> :         #   In the exception name we have the line number,
> :         # just in case we want to fine tune error handling
> :     }
> First of all, note that unless command3 is return, the always block
> is going to execute regardless of whether there has been an error.

    Well, I was going to use a test in the always block to see if an
exception was thrown, using catch or testing for "EXCEPTION" and
"TRY_BLOCK_ERROR" manually. That's not an issue.

> How about:
> 
>     function common_error() {
> 	# Here we catch and handle the common error
> 	# In the ERROR_LINE variable we have the line number,
> 	# and in the ERROR variable we have the $? status,
> 	# just in case we want to fine tune error handling
>     }
> 
>     trap 'ERROR=$?; ERROR_LINE=$LINENO; return $ERROR' ZERR
>     trap common_error EXIT
> 
>     command1
>     command2
>     command3
> 
>     trap - EXIT ZERR
> 
> Note also for reference that
>     trap 'return $?' ZERR
> is roughly equivalent to
>     setopt ERR_RETURN

    Man, you're the f. boss. I NEVER thought about this, which
doesn't need throw nor an always block. Thanks a lot for the help,
Bart, this is a very good solution, much better, even, than using
always blocks.

    Just one note: why should be always blocks needed at all if you
can use this kind of solutions? As long as you don't cause ZERR to be
raised in "common_error()", this solution is much better because you
can fine tune (using the "trap" builtin) when do you want to do
common handling and when you don't. The only difference I can see is
that code in an always block is executed in the current environment
and code in "common_error()" is not.

    Raúl Núñez de Arenas Coronado

-- 
Linux Registered User 88736 | http://www.dervishd.net
http://www.pleyades.net & http://www.gotesdelluna.net
It's my PC and I'll cry if I want to...



Messages sorted by: Reverse Date, Date, Thread, Author