The mechanism for maintaining complex food webs has been a central issue in ecology because theory often predicts that complexity (higher the species richness, more the interactions) destabilizes food webs. Although it has been proposed that prey anti-predator defence may affect the stability of prey–predator dynamics, such studies assumed a limited and relatively simpler variation in the food-web structure. Here, using mathematical models, I report that food-web flexibility arising from prey anti-predator defence enhances community-level stability (community persistence and robustness) in more complex systems and even changes the complexity–stability relationship. The model analysis shows that adaptive predator-specific defence enhances community-level stability under a wide range of food-web complexity levels and topologies, while generalized defence does not. Furthermore, while increasing food-web complexity has minor or negative effects on community-level stability in the absence of defence adaptation, or in the presence of generalized defence, in the presence of predator-specific defence, the connectance–stability relationship may become unimodal. Increasing species richness, in contrast, always lowers community-level stability. The emergence of a positive connectance–stability relationship however necessitates food-web compartmentalization, high defence efficiency and low defence cost, suggesting that it only occurs under a restricted condition.