\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#329: Try/Catch/Finally syntax}
\date{September 22, 2008}
\author{Trevor Davel}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#329}&\textbf{Try/Catch/Finally syntax}\\\hline
Author&

Trevor Davel \tipmail{twylite}{crypt.co.za}
\\
Created&Monday, \(\text{22}^{\text{nd}}\) September 2008\\
Type&Project\\
Tcl Version&\(8.6\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.9 $\\
Obsoletes&89\\
Post History&\\
Discussions To&http://wiki.tcl.tk/21608\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes the addition of new core commands to improve the exception handling mechanism. It supercedes \cite{tip89} by providing support for the error options dictionary introduced in Tcl 8.5 by \cite{tip90}.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

See \cite{tip89} for general rationale for enhancing exception handling.

The \textbf{try} syntax presented here is not intended to replace \textbf{catch}, but to simplify the expression of existing exception/error handling techniques, leading to greater code clarity and less error-prone workarounds for \textbf{finally} blocks. There is no deficiency in the functionality of Tcl's exception handling mechanisms --- what is lacking is a more readable syntax and a standard for behaviour across packages for the common case of catching a subset errors or exceptions that are thrown from within a particular block of code.

In Tcl 8.4 exceptions could be caught using \textbf{catch}, and exception information was available via the \textbf{catch} return value and resultvar. If the return value was TCL\_ERROR (1) then the globals \textbf{::errorCode} and \textbf{::errorInfo} would be set according to the exception raised. \cite{tip89} was written to work with this model, such that a catch handler (in a \textbf{try...catch}) would be able to capture the resultvar, errorCode and errorInfo.

Tcl 8.5 implements \cite{tip90} which extends \textbf{catch} to allow an additional dictionary of options (error information) to be captured. These options supercede the \textbf{::errorInfo} and \textbf{::errorCode} globals (though those are still supported for backward compatibility). It is therefore logical to extend/correct the syntax of \cite{tip89} to support the options dictionary in preference to the older mechanism for capturing exception information.

Benefits of adding this functionality to the core:
\begin{itemize}
\item{}
Bring to Tcl a construct commonly understood and widely used in other languages.
\item{}
A standard for identifying categories/classes of errors, which will improve interoperability between packages.
\item{}
A byte-coded implementation would be significantly faster than the Tcl implementation that is presented.
\end{itemize}

\section{Specification}

\begin{quote}
\textbf{try} \textit{body} ?\textit{handler} ...? ?\textbf{finally} \textit{body}?
\end{quote}

\begin{quote}
\textbf{throw} \textit{type message}
\end{quote}

The \textbf{try} body is evaluated in the caller's scope. The handlers are searched in order of declaration until a matching one is found, and the associated body is executed. If no matching handler is found then \textbf{try} returns the result of the \textbf{try} body (exceptions will propagate up the stack as usual); otherwise \textbf{try} returns the result of the handler body (exceptions will propagate up the stack as usual).

Only one handler body (that of the first matching handler) will be executed. If the handler body is the literal string ``\textbf{-}'' then the body for the subsequent handler will be used instead. It is an error for the last handler's body to be a literal ``\textbf{-}''.

The \textbf{finally} body (if present) will be executed last, and is always executed whatever the results of the try and handler bodies (excepting resource exhaustion or cancellation). If the \textbf{finally} body returns an exceptional code then this will become the result of \textbf{try}, otherwise the result of the \textbf{finally} body is ignored.

Since the \textbf{trap} handlers in the \textbf{try} control structure are filtered based on the exception's \textbf{-errorcode}, it makes sense to have a command that will encourage the use of error codes when throwing an exception. \textbf{throw} is merely a reordering of the arguments of the \textbf{error} command. \textit{type} is treated as a list by \textbf{trap} (see below), which maintains compatibility with the description of ::errorCode given in \textbf{tclvars}.

\subsection{Handlers}

Each handler is identified by a keyword. The fields following the keyword indicate what exceptions or errors are matched by the handler, the variables into which the result of the \textbf{try} body will be assigned (in the caller's scope), and the body of the handler.

\begin{quote}
\textbf{on} \textit{code \{?resultVar ?optionsVar?\} body}
\end{quote}

The \textbf{on} handler allows exact matching against the exceptional return code (the integer value that would be returned by \textbf{catch}). The \textit{code} may be given as an integer or one of the magic keywords \textbf{ok} (0), \textbf{error} (1), \textbf{return} (2), \textbf{break} (3), \textbf{continue} (4).

\begin{quote}
\textbf{trap} \textit{pattern \{?resultVar ?optionsVar?\} body}
\end{quote}

The \textbf{trap} handler allows list prefix matching against the \textbf{-errorcode} from the options when the exceptional return code is TCL\_ERROR (1). Given a \textit{pattern} and an \textit{errorcode}, a list prefix match is successful if for every element in \textit{pattern} there is a corresponding and identical element in \textit{errorcode}. Trailing elements in \textit{errorcode} are ignored.

Notes \& clarifications:
\begin{itemize}
\item{}
Handlers are searched in order of declaration (left-to-right). One consequence of this search order is that an \textbf{on error} handler will supercede all subsequent \textbf{trap} handlers.
\item{}
Any unhandled exception propagates.
\item{}
The result of the last executed body (other than the \textbf{finally} body) is the result of the \textbf{try}. Exceptions in any \textit{handler} body or in the \textbf{finally} replace the existing exception and propagate.
\item{}
If any exception is replaced (by an exception in a handler body or in the \textbf{finally} body) then the new exception shall introduce into its options dictionary the field \textbf{-during} that contains the options dict of the exception that was replaced.
\item{}
If any errorcode happens to be not a list, a \textbf{trap} handler will be unable to process it. However, this should only happen in cases where there is a bug or other problem elsewhere, since \textbf{return} is documented to require the errorcode to be a list.
\end{itemize}

\section{Examples}

Simple example of \textbf{try}/\textit{handler}/\textbf{finally} logic in Tcl using currently available syntax:
\begingroup\small\begin{verbatim}
 proc read_hex_file {fname} {
    set f [open $fname "r"]
    set data {}
    set code [catch {
       while { [gets $f line] >= 0 } {
          append data [binary format H* $line]
       }
    } em opts]
    if { $code != 0 } {
       dict set opts -code 1
       set em "Could not process file '$fname': $em"
    }
    close $f
    return -options $opts $em
 }
\end{verbatim}
\endgroup

And the same example rewritten to use [\textbf{try}]:
\begingroup\small\begin{verbatim}
 proc read_hex_file {fname} {
    set f [open $fname "r"]
    set data {}
    try  {
       while { [gets $f line] >= 0 } {
         append data [binary format H* $line]
       }
    } trap {POSIX} {} {
       puts "POSIX-type error"
    } on error {em} {
       error "Could not process file '$fname': $em"
    } finally {
       close $f
    }
 }
\end{verbatim}
\endgroup

This illustrates how the intent of the code is more clearly expressed by [\textbf{try}].

\section{References}
\begin{itemize}
\item{}
Tcl 8.4 catch [\url{http://www.tcl.tk/man/tcl8.4/TclCmd/catch.htm}]
\item{}
Tcl 8.5 catch [\url{http://www.tcl.tk/man/tcl8.5/TclCmd/catch.htm}]
\end{itemize}

\section{Rejected Alternatives}

Various alternatives are discussed on the wiki [\url{http://wiki.tcl.tk/21608}] along with reasons for their rejection.

\section{Future Extensions}

No specific future exceptions are planned, but \textbf{try} could be extended by adding new handler keywords and/or introducing new varnames to the variables list that is associated with each handler.

It is recommended that new handlers maintain the established convention:

\begin{quote}
\textbf{keyword} \textit{criteria \{?resultVar ?optionsVar?\} body}
\end{quote}

\section{Reference Implementation}

A reference implementation can be found at [\url{http://www.crypt.co.za/pub/try-1.tcl}]

\section{Thanks}

Thanks in particular to DKF, NEM and JE for their feedback and suggestions on this TIP.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#2}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#89]{tip89}
Tom Wilkason,
Frank Pilhofer,
\emph{Try/Catch Exception Handling in the Core},
on-line at \url{http://purl.org/tcl/tip/89.html}
\bibitem[TIP \#90]{tip90}
Don Porter,
Donal K. Fellows,
\emph{Enable [return -code] in Control Structure Procs},
on-line at \url{http://purl.org/tcl/tip/90.html}
\end{thebibliography}
\end{document}
