"... in the end he managed to Apparate out, even though he'd never passed his test. He nearly died doing it. Everyone thought it was a really good story, but I was the only one who realized what it meant - ..."
Harry Potter and the Half-blood Prince
I think the sentence "He nearly died doing it" could mean:
He nearly died while doing it(Apparated out).
He was trying very hard(probably at any cost) to Apparate out.
I don't know which one is correct. What's it supposed to mean here?