If the pregnancy ends spontaneously before week 22, it is called a miscarriage. Most miscarriages happen during the first 12 weeks of pregnancy. After 12 weeks they are called late miscarriages. Sometimes you can have a very early miscarriage, already right after a positive pregnancy-test. A miscarriage is nature's way of ending something that is not viable.
About every fifth pregnancy ends with a miscarriage, usually before week 12. The most common reason being that there is something wrong with the cell division and there is nothing one can do to prevent this from happening. It is natural to feel sorrow after a miscarriage. Allowing oneself to be sad and go through a grieving process makes it easier to go on with your life afterward.