Carapaz (Movistar), launched his sprint early and held off Australian Caleb Ewan (Lotto Soudal) and Diego Ulissi (UAE Team Emirates) on the uphill finish at the end of a rolling 235km route from Orbetello to Frascati.
Roglic (Jumbo-Visma) was the only major favourite to avoid a crash which split the peloton inside the final six kilometres and he finished two seconds behind Carapaz.
"I didn't expect to win today," Carapaz said. "Our plan was just to protect Mikel Landa to not lose time but a crash at the end changed everything. I was up against sprinters for the stage win so I had to anticipate their action. The moment I chose to attack was perfect."
Simon Yates (Mitchelton-Scott) and Vincenzo Nibali (Bahrain-Merida), second and third in the overall standings, were caught up in the crash and finished 16 seconds behind Roglic.
Roglic has worn the leader's pink jersey since winning the opening time trial on Saturday and extended his lead to 35 seconds ahead of Yates and 39 ahead of Nibali.
Tom Dumoulin (Sunweb) was the biggest casualty of the crash. The bloodied 2017 champion crossed the line more than four minutes behind Roglic, his chance to win the overall, over.
“Puccio from Ineos crashed, I think he touched a wheel or something and he took me and [Ion] Izaguirre (Astana) with him," Dumoulin said.
"I was in the front of the bunch and just couldn’t avoid it. There are no fractures which is good but my knee is very swollen. I wasn’t able to push any power in the last few kilometres so I don’t know how I will be tomorrow; the GC is for sure gone."
Prior to the stage, Colombian Juan Sebastian Molano was withdrawn from the race by his Team UAE Emirates after internal tests gave “unusual physiological results”.
The Middle Eastern registered outfit said in a statement that Molano would be provisionally suspended to “undergo further testing in collaboration with the International Cycling Union”.
The fifth stage is a mainly flat 140km route from Frascati to Terracina.