Debugging Techniques in Programming
1. Breakpoints:
By setting breakpoints in the code, you can pause the program at specific points, check variables, and closely examine the program’s current state.
Using Breakpoints in python:
import pdb
def example_function():
# Code to be executed before breakpoint
x = 5
y = 10
# Set a breakpoint
pdb.set_trace()
# Code to be executed after breakpoint
result = x + y
print("Result:", result)
# Call the function
example_function()
2. Step Through:
Examining the code line by line aids in identifying the precise location of an error.
Stepping Through Code in C:
#include <stdio.h>
int main() {
// Sample variables
int a = 5;
int b = 10;
int result;
// Set a breakpoint by adding a dummy condition
if (a == 0) {
printf("Breakpoint\n");
}
// Code to be executed before breakpoint
result = a + b;
// Output the result
printf("Result: %d\n", result);
// Rest of the code
return 0;
}
Output
Result: 15
3. Watch Variables:
Observing variable values while the program runs provides insights into any unexpected behavior.
Watching Variables in C++:
#include <iostream>
using namespace std;
int main() {
// Sample variables
int a = 5;
int b = 10;
int result;
// Set a breakpoint by adding a dummy condition
if (a == 0) {
cout << "Breakpoint" << endl;
}
// Code to be executed before breakpoint
result = a + b;
// Output the result
cout << "Result: " << result << endl;
// Rest of the code
return 0;
}
Watching Variables in Java:
public class Main {
public static void main(String[] args) {
// Sample variables
int a = 5;
int b = 10;
int result;
// Set a breakpoint by adding a dummy condition
if (a == 0) {
System.out.println("Breakpoint");
}
// Code to be executed before breakpoint
result = a + b;
// Output the result
System.out.println("Result: " + result);
// Rest of the code
}
}
Output
Result: 15
Error Handling in Programming
In Programming, errors occur. Our code needs to be prepared for situations when unexpected input from users occurs, division by zero occurs, or a variable name is written incorrectly. To prevent unexpected events from crashing or having unexpected outcomes, error handling involves putting in place methods to identify, report, and manage problems.
Table of Content
- What is Error Handling in Programming?
- Try, Catch, Except, and Finally Blocks
- Comparison between Try, Catch/ Except and Finally Blocks
- Common Errors and Debugging
- Debugging Techniques in Programming
- Debugging Tools in Programming
- Best Practices for Error Handling in Programming