There is a theory in criminal law called "mens rea." That's Latin for "guilty mind." The gist of the theory is that if an individual charged with a crime didn't have criminal intent at the time of the act, it should be possible to use that in the person's defense. Whether it makes sense to try that tactic depends on the circumstances of the case.
It's worth noting, however, that it is very possible for a person to violate the law without knowing it. There are so many laws on the books that it becomes easy to unintentionally step across legal lines. For example, depending on the laws of your state, you could find yourself facing criminal charges if you host a friendly poker game. If you decide to share your password for an online subscription service like Netflix or HBO Now so a friend can use it, you could be indicted under federal law.
In Minnesota, hanging something like a rosary or graduation tassel from the rearview mirror, is illegal. If you carry someone else's prescription medication, give your prescription pills to someone else or carry a daily dose in something other than its prescription bottle, you could suddenly and unexpectedly wind up facing drug charges.
Regardless of whether you intended to break the law or not, the reality is that authorities can choose to prosecute when they believe they can win a conviction. And considering that the consequences of a guilty verdict, whether it is obtained by plea deal or results from trial, can include incarceration, significant fines, probation, and a criminal record that stays with you into the future, the importance of contacting an experienced attorney immediately becomes clear.