Casting While Threatened
Casting a spell takes a significant amount of concentration, forcing you to lower your defenses briefly. When you cast a spell, it gives targets threatening you in melee a chance to make an attack of opportunity against you (see Attack of Opportunity on page 248), unless the spell specifies otherwise—normally only the case for a few spells with a range of touch. If this attack of opportunity hits and damages you, you fail to cast the spell and lose the spell slot. For more information about threatened squares, see page 255.
Source
Core Rulebook pg. 246