Skip to content

Instantly share code, notes, and snippets.

@DrDougPhD
Created September 13, 2016 22:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrDougPhD/74ef412516e6ef760da1618b64d6ee59 to your computer and use it in GitHub Desktop.
Save DrDougPhD/74ef412516e6ef760da1618b64d6ee59 to your computer and use it in GitHub Desktop.
LaTeX Exception Handling Pseudocode (i.e. Try-Catch-Finally blocks) for the algorithmicx package
%% try-catch-finally.tex
%% Copyright 2016 Doug McGeehan <djmvfb@mst.edu>
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
% http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of LaTeX
% version 2005/12/01 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is Doug McGeehan.
%
% This work consists of the file try-catch-finally.tex.
%
% Inspired by exception handling as done in Python:
% https://docs.python.org/3/tutorial/errors.html
%
% Note: I couldn't get an "else" block to work.
\documentclass[11pt]{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\algblock[TryCatchFinally]{try}{endtry}
\algcblock[TryCatchFinally]{TryCatchFinally}{finally}{endtry}
\algcblockdefx[TryCatchFinally]{TryCatchFinally}{catch}{endtry}
[1]{\textbf{catch} #1}
{\textbf{end try}}
\begin{algorithmic}[1]
\try
\State{Code that can cause an error\dots}
\catch{Expected exception}
\State{Code that can properly handle the expected exception\dots}
\catch{Any other exception}
\State{Code that can properly handle all other exceptions\dots}
\State{(i.e. the \texttt{else} block)}
\finally
\State{Code that always executes before leaving try-block}
\State{\, whether or not an exception occurred (i.e. \emph{clean-up})\dots}
\endtry
\end{algorithmic}
\end{algorithm}
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment