## 22.1 Introduction

What do you do when R code throws an unexpected error? What tools do you have to find and fix the problem? This chapter will teach you the art and science of debugging, starting with a general strategy, then following up with specific tools.

I’ll show the tools provided by both R and the RStudio IDE. I recommend using RStudio’s tools if possible, but I’ll also show you the equivalents that work everywhere. You may also want to refer to the official RStudio debugging documentation which always reflects the latest version of RStudio.

NB: You shouldn’t need to use these tools when writing new functions. If you find yourself using them frequently with new code, reconsider your approach. Instead of trying to write one big function all at once, work interactively on small pieces. If you start small, you can quickly identify why something doesn’t work, and don’t need sophisticated debugging tools.

### Outline

• Section 22.2 outlines a general strategy for finding and fixing errors.

• Section 22.3 introduces you to the traceback() function which helps you locate exactly where an error occurred.

• Section 22.4 shows you how to pause the execution of a function and launch environment where you can interactively explore what’s happening.

• Section 22.5 discusses the challenging problem of debugging when you’re running code non-interactively.

• Section 22.6 discusses a handful of non-error problems that occassionally also need debugging.