Can rocket candy explode during the preparation?
See James Yawn's website ${\it Recrystalized\; Rocketry}$, which is all about solid propellant rocketry of the type you're interested in. It's really an exceptionally comprehensive site.

Can this mixture explode during the heating somehow?

It appears that it's more likely to catch fire, and do so rather vigorously, as in cases where it's exposed to a spark or an open flame. Because the system (pan and mixture of $\ce{KNO3}$ and sugar) would be open to the atmosphere (and not confined to a fixed volume), there's more of a risk of fire than of an explosion. As reported by James Yawn in the subsection on &quot;Skillet Rcandy&quot;:

This stuff looks innocent enough in the pan.  But if you have ever seen a quantity this size burn you will have more respect for it.  This batch could send a tongue of flame 20 feet in the air and engulf the person stirring it, if only briefly.  Burns to the body would likely be second degree, and I am willing to tolerate that level of risk.  But eyeballs don't recover from this kind of trauma easily.

See this safety page from James Yawn's site.

Or it can just burn, not explode?

Yes, it can just burn: that's essentially what's going on in the rocket engine. The exhaust from the burn is channeled in one direction (${\it via}$ the hollow core in the engine itself), resulting in thrust in the other direction.

How to prevent it, and do it the most secure way?

From James Yawn's site:

Basic Safety Precautions
At present, I do NOT recommend making this propellant in a household kitchen.
Make small batches only!  No more than one standard recipe, which yields about 160 grams of propellant.
Wear protective gear. You should have a full-face shield, long sleeved heavy cotton shirt, heavy apron and heat-resistant gloves.  These must be worn at appropriate points in the process.
Do not allow children or rambunctious pets in the room where you are working.
Do not allow distracting, inattentive, inebriated or otherwise incompetent adults in the room, especially if they smoke.
Be vigilant of possible sources of sparks, flame, or high temperature that could ignite propellant on contact.
If you smoke, place your cigarettes and lighter in another room so you will not light up unconsciously.
Clear your work-area of any flammable materials.
Have a good fire extinguisher available. Also a 5-gallon bucket of water nearby and a garden hose outside.
Make sure there is good ventilation, and a quick escape route to fresh air.
Avoid stupid rocket tricks.
Avoid excessive exposure to Potassium Nitrate.

All of the above points are elaborated upon at the linked page.