Common Errors and Debugging
Understanding common errors is essential for proficient error handling. Syntax errors emerge during the compilation phase and are relatively easy to identify. In contrast, runtime errors manifest during program execution and can involve a wide range of issues, such as division by zero, file not found, or invalid input.
Debugging is the process of identifying and rectifying errors. Some tried-and-true debugging techniques include:
- Print Statements: Placing print statements in the code strategically helps in tracing the program’s execution and identifying errors more effectively.
- Logging: Using logging libraries captures important details about how the program is running, making it easier to trace errors.
- Code Reviews: Having someone else review your code can reveal possible problems that might cause errors.
Lets see some common errors and how are they handled:
1. Handling File Not Found Error:
//Handling File Not Found Error:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
try {
ifstream file("nonexistent_file.txt");
if (!file.is_open()) {
throw ios_base::failure("FileNotFoundError");
}
// Rest of the code
} catch (const ios_base::failure& file_error) {
cerr << file_error.what() << endl;
}
return 0;
}
//Handling File Not Found Error:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
perror("FileNotFoundError");
}
// Rest of the code
return 0;
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File file = new File("nonexistent_file.txt");
try {
Scanner scanner = new Scanner(file);
// Rest of the code
scanner.close();
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundError: " + e.getMessage());
}
}
}
#Handling File Not Found Error:
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as file_error:
print(f"FileNotFoundError: {file_error}")
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
// Open the file for reading
using (StreamReader file = new StreamReader("nonexistent_file.txt"))
{
// If the file is opened successfully, read its contents
Console.WriteLine(file.ReadToEnd());
}
}
catch (FileNotFoundException)
{
// Handle the FileNotFoundException
Console.WriteLine("FileNotFoundError: File not found.");
}
catch (IOException e)
{
// Handle other IO exceptions
Console.WriteLine($"IOException: {e.Message}");
}
catch (Exception e)
{
// Handle other exceptions
Console.WriteLine($"An error occurred: {e.Message}");
}
}
}
const fs = require('fs');
// Main function
function main() {
const filePath = 'nonexistent_file.txt';
// Attempt to read the file
fs.readFile(filePath, 'utf8', (err, data) => {
// If an error occurs, handle it
if (err) {
// Check if the error is due to file not found
if (err.code === 'ENOENT') {
console.error(`FileNotFoundError: ${err.message}`);
} else {
// Print other errors
console.error(`Error: ${err.message}`);
}
return;
}
// If file is read successfully, do something with the data
console.log(data);
});
}
// Call the main function
main();
2. Handling Invalid Input Error:
// Handling Invalid Input Error:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string user_input;
cout << "Enter a number: ";
getline(std::cin, user_input);
int value;
istringstream input_stream(user_input);
if (!(input_stream >> value)) {
cerr << "InvalidInputError" << endl;
}
// Rest of the code
return 0;
}
// Handling Invalid Input Error:
#include <stdio.h>
int main() {
char user_input[256];
printf("Enter a number: ");
fgets(user_input, sizeof(user_input), stdin);
int value;
if (sscanf(user_input, "%d", &value) != 1) {
fprintf(stderr, "InvalidInputError\n");
}
// Rest of the code
return 0;
}
/* Handling Invalid Input Error */
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
String userInput = scanner.nextLine();
int value;
try {
value = Integer.parseInt(userInput);
// Rest of the code
} catch (NumberFormatException e) {
System.err.println("InvalidInputError");
}
} catch (Exception e) {
System.err.println("Error reading input: " + e.getMessage());
} finally {
scanner.close(); // Close the scanner to prevent resource leaks
}
}
}
# Handling Invalid Input Error:
user_input = input("Enter a number: ")
try:
value = int(user_input)
except ValueError:
print("InvalidInputError")
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter a number: ', (userInput) => {
try {
const value = parseInt(userInput);
if (isNaN(value)) {
console.error('InvalidInputError');
} else {
// Rest of the code
}
} catch (error) {
console.error('InvalidInputError');
} finally {
rl.close(); // Close the readline interface to prevent resource leaks
}
});
3. Assertion Error:
#include <cassert>
#include <iostream>
using namespace std;
int main() {
int value = -5;
// Use assert to check a condition
assert(value > 0 && "Value must be greater than 0");
// Rest of the code
return 0;
}
#include <assert.h>
int main() {
int value = -5;
// Use assert to check a condition
assert(value > 0 && "Value must be greater than 0");
// Rest of the code
return 0;
}
/* Assertion Error */
public class Main {
public static void main(String[] args) {
int value = -5;
// Use assert to check a condition
assert value > 0 : "Value must be greater than 0";
// Rest of the code
System.out.println("Program continues");
}
}
# Assertion Error
value = -5
# Use assert to check a condition
assert value > 0, "Value must be greater than 0"
# Rest of the code
print("Program continues")
// Custom assert function to check a condition
function assert(condition, message) {
if (!condition) {
throw new Error("AssertionError: " + message);
}
}
// Main function
function main() {
let value = -5;
// Use assert to check a condition
assert(value > 0, "Value must be greater than 0");
// Rest of the code
console.log("Program continues");
}
// Call the main function
main();
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