So if you get caught in the target country spying on them, you'll get prosecuted and then go to jail or get executed. If you don't, or if you spy remotely (SIGINT), you won't. Simple as that. Espionage is older than nation states and is legalized in countries doing the spying - that's why you have official intelligence agencies.