A Theoretical Understanding of Chain-of-Thought: Coherent Reasoning and Error-Aware Demonstration