This is called the gluing lemma. It applies to finitely many closed sets and arbitrarily many open.

So, suppose that where are closed subspaces of and and are continuous functions such that then is well-defined since agree on the intersection of their domains. Also, it's continuous since if is closed it is easy to see that . But, since are continuous are closed subspaces of respectively but since they themselves are closed subspaces of it follows that so are . Thus, is the finite union of closed sets and thus closed. The conclusion follows.

This can be generalized, as I said, to a finite partition of closed sets or an arbitary partition of open ones.