0

It appears that there is no such try and catch blocks in algorithm2e. Is there a way to add custom blocks for try and catch in algorithm2e?

There is a solution in GitHub which shows how this can be done using the algorithmicx/algpseudocode package. I would like to do this in algorithm2e.

2

Took a better look at the docs and found an applicable solution:
\SetKwProg{Cmd}{block}{suffix}{end}
The suffix and end parts are optional

A minimum working example (MWE):

\usepackage[linesnumbered, ruled]{algorithm2e}

\begin{document}

\begin{algorithm}[t]
  \SetKwInOut{Input}{Input}
  \SetKwInOut{Output}{Output}
  \SetKwProg{try}{try}{:}{}
  \SetKwProg{catch}{catch}{:}{end}
  \Input{Array $a$ and index $i$}
  \Output{what the procedure returns}

  \try{}{
    $v \gets a[i]$
  }
  \catch{IndexOutOfBoundsException}{
    $v \gets -1$
  }
  \Return $v$
  \caption{Exception handling code}
  \label{alg:exep}
\end{algorithm}

\end{document}

Output:

enter image description here

  • Does anyone else think it would be better without the colon suffix? – Ébe Isaac Sep 15 '18 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.