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:

C++
//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;
}
C
//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;
}
Java
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());
        }
    }
}
Python
#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}")
C#
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}");
        }
    }
}
JavaScript
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:

C++
// 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;
}
C
// 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;
}
Java
/* 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
        }
    }
}
Python
# Handling Invalid Input Error:

user_input = input("Enter a number: ")
try:
    value = int(user_input)
except ValueError:
    print("InvalidInputError")
JavaScript
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:

C++
#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;
}
C
#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;
}
Java
/* 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");
    }
}
Python
# 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")
JavaScript
// 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.

Error Handling in Programming

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

Similar Reads

What is Error Handling in Programming?

Error handling in Programming is a fundamental aspect of programming that addresses the inevitable challenges associated with unexpected issues during code execution. These issues may range from simple typographical errors to more intricate runtime errors that manifest during the program’s operation. The effectiveness of error handling is crucial in the development of software that is not only functional but also resilient and dependable....

Try, Catch/ Except and Finally Blocks:

Within the domain of programming languages, error handling commonly incorporates constructs such as ‘try’, ‘catch’ (or ‘except’), and ‘finally’ blocks. The ‘try’ block encapsulates the code where an error might occur, while the ‘catch’ (or ‘except’) block is responsible for capturing and handling the error. The optional ‘finally’ block ensures the execution of specific code, irrespective of whether an error occurs or not....

Comparison Between Try, Catch/ Except and Finally Blocks:

BlockPurposeExecution FlowtryEncloses the code where an exception might occur.Code inside the try block is executed.catch/exceptCatches and handles exceptions raised in the try block.If an exception occurs in the try block, the corresponding catch/except block is executed.finallyContains code that will be executed regardless of whether an exception occurred or not.Executed after the try block, whether an exception occurred or not....

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 Techniques in Programming:

1. Breakpoints:...

Debugging Tools in Programming:

There are many tools available to help in debugging:...

Best Practices for Error Handling in Programming:

To enhance error handling, follow these best practices:...