[Tex/LaTex] addtocontents not working with certain other packages

packagestable of contents

This is a follow up question on this

How do I change the toc dept mid document while using packages (in this case only mathtools).

An example:

\documentclass[a4paper,10pt,oneside]{book}

\usepackage{mathtools}

\begin{document}

 \frontmatter          

 \chapter{hello}
 \section{hello}
 \subsection{hello}
 \subsubsection{hello}

 \setcounter{tocdepth}{3}
 \tableofcontents

 \mainmatter

 \chapter{hello}
 \section{hello}
 \subsection{hello}
 \subsubsection{hello}

 \chapter{hello}
 \section{hello}
 \subsection{hello}
 \subsubsection{hello}

 \appendix

 \addtocontents{toc}{\setcounter{tocdepth}{0}}

 \chapter{hello}
 \section{hello}
 \subsection{hello}
 \subsubsection{hello}

 \chapter{hello}
 \section{hello}
 \subsection{hello}
 \subsubsection{hello}

\end{document}

This example generates an error and very strangely puts an exclamation mark in the ToC as you can see here
example

however when I comment out the \usepackage{mathtools} it suddenly works again or replacing it with a different package such as \usepackage[T1]{fontenc} also generates no errors.

But this is not limited to just this specific package, certain other packages also introduce the same behavior (I just took this package to keep the example small).

Best Answer

In addition to my comment above: You have to add a \protect so that the line looks like \addtocontents{toc}{\protect\setcounter{tocdepth}{0}}. For an explanation you may refer to Problems with mathtools package (or to egreg's elaborated answer below).