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.

1 Answer 1

4

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .