[Tex/LaTex] Exception handling pseudocode (try-catch) for algorithm2e package

algorithm2ealgorithms

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.

Best Answer

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