"Debugging" refers to the process of finding and fixing errors, or "bugs" in a program. The term comes from Admiral Grace Hopper who, while working on an early computer in the 1940s found a moth stuck in the computer. Now bugs are rarely caused by actual insects, but by errors in our code.
A "debugger" is a program that assists us in the task of debugging. Today we will look at using the debugger integrated into NetBeans.
A debugger works by letting you run through your program one line at a time. While the program is running you can look at the values of your variables and see what your code is doing at run time.
In order to start debugging, you need to create a "break point" which is a location in your code where the debugger will pause your program and give control back to you.
To create a breakpoint in NetBeans, right-click on the line number of the line in question, then click "Breakpoint" and the "Toggle Breakpoint". You can also just left-click on the line number.
For example, if we want to try to investigate why this factorial program is not working correctly, we could add a breakpoint.
A good spot would be at the top of the "fact" function, on line 8.
Once we have a breakpoint in place, we can start debugging. There are a few ways to do this:
Now the debugger will start and our program will begin to run until it hits a breakpoint. You can enter a number in the nextInt( ) statement for the factorial program. Once you do that, it will hit the breakpoint and pause execution.
At the bottom of the screen are a number of new windows related to debugging. The "Variables" window is probably the one we're most interested in.
The debugger allows you to step through your code line by line. To do this, it offers a couple of ways to step through code:
Both of these have toolbar icons, and keyboard shortcuts.
Can we step through the factorial program and find the error?
A debugger is an invaluable tool as a programmer. It allows you to visualize your code, inspect variables at runtime, and see the moment where things go awry.
For simple programs, they may not be necessary, but for larger programs, it's too hard to visualize and reason about code without a debugger.
Try out using the debugger on this program which reads in a set of numbers from the user and tries to determine whether they are in ascending order or not. There are two problems with this code. One problem causes it to crash when you run it, the other will cause it to produce incorrect results.
Fix both of them and turn in the working version to me.
Even if you can figure this out without using the debugger, you should get familiar with debugging with the debugger, as it will help you at some point!
Copyright © 2022 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.