# excludecomment fails when used with newenvironment

I can hide a proof environment using the comment package:

\documentclass{article}
\usepackage{comment,amsthm}
\excludecomment{proof}
\begin{document}
This is always printed.
Hide this.
\end{proof}
\end{document}


When I try to do the same with an added newenvironment command, i.e.,

\documentclass{article}
\usepackage{comment,amsthm}
\begin{document}
This is always printed.
Hide this.
\end{document}


I get the error:

Any ideas why?

The reason for this is because the assigned comment environment <env> doesn't process the construction \begin{<env>}...\end{<env>} as a regular group (from the documentation):

Note: for an included comment, the \begin and \end lines act as if they don't exist. In particular, they don't imply grouping, so assignments &c are not local.

A lengthier explanation: The expansion of \begin{answer} does result in \begin{proof}[Answer], but the group is immediately closed before searching for \end{answer}. Internally, LaTeX keeps track of which group you're in with every call to \begin. The macro responsible for holding the information on the current environment is \@currenvir which, based on your definition

\newenvironment{answer}
{\end{proof}}


holds proof rather than answer after expanding \begin{answer}. Ultimately the comment package's search finds \end{answer}, but this fails the LaTeX test for a matching environment \begin, resulting in the posted error.

In short, it's processed differently than expected.

A way around this is to set the nested environment using a command-form:

\documentclass{article}

\usepackage{comment,amsthm}

\begin{document}

This is always printed.

Note the requirement that the \end{<env>} for a commented <env> should be on a line of its own without spaces: