Most code has bugs in it. The reason for that is that the word "bugs" is really loose and covers a wide spectrum of "things" from "doesn't meet the requirements" to "fails in various conditions and throws an error". Because of this, the process of debugging is as important if not more important than the process of coding. Many studies show that the total amount of time spent debugging code is often more than the amount of time it took to write the code originally.
The best thing you can do is to do everything you can to reduce the amount of time you spend debugging. You can do this in a variety of ways: spending more time up front designing and architecting your code, spending time writing code for testing your code and testing your code thoroughly, using functions that are known to be "correct" rather than writing your own, using an editor that helps you develop quality code, writing code that is adequately commented and very readable, and working with other people while coding (peer review catches many problems very quickly).
Practicing those things will do a lot to reduce the amount of debugging you will have to do, though it's unlikely it will eliminate the need to debug altogether.
The art of debugging is to look at a set of symptoms (errors, circumstances, steps to repeat the error, ...), understand the underlying problem(s), and fix them.
The best results would be to fix the problem without getting frustrated and to increase the quality of the code involved.