Module 07: Exception Handling and File I/O - Exercises

Practice exercises to master robust error handling and file operations in Java

Practice Exercises

Exercise 1: Basic Exception Handling

Practice using try-catch blocks to handle common exceptions.

Requirements:

  • Create a method that divides two numbers and handles ArithmeticException
  • Create a method that converts a string to integer and handles NumberFormatException
  • Create a method that accesses an array element and handles ArrayIndexOutOfBoundsException
  • Use try-catch blocks with appropriate exception types
  • Print meaningful error messages for each exception
Sample Code:
public class ExceptionPractice {
    public static double divideNumbers(int a, int b) {
        try {
            return (double) a / b;
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed");
            return 0.0;
        }
    }
    
    public static int parseInteger(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            System.out.println("Error: Cannot convert '" + str + "' to integer");
            return 0;
        }
    }
    
    public static int getArrayElement(int[] array, int index) {
        try {
            return array[index];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index " + index + " is out of bounds");
            return -1;
        }
    }
}

Exercise 2: Try-with-Resources

Practice using try-with-resources for automatic resource management.

Requirements:

  • Create a method that reads from a file using try-with-resources
  • Create a method that writes to a file using try-with-resources
  • Handle FileNotFoundException and IOException
  • Ensure resources are automatically closed
  • Create a simple text file for testing
Sample Code:
import java.io.*;
import java.nio.file.*;

public class FileIOPractice {
    public static void readFile(String filename) {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
    
    public static void writeFile(String filename, String content) {
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filename))) {
            writer.write(content);
            System.out.println("File written successfully");
        } catch (IOException e) {
            System.out.println("Error writing file: " + e.getMessage());
        }
    }
}

Exercise 3: Custom Exceptions

Create and use custom exception classes.

Requirements:

  • Create a custom exception class called InvalidAgeException
  • Create a custom exception class called InsufficientFundsException
  • Create a method that throws InvalidAgeException for ages less than 0 or greater than 150
  • Create a method that throws InsufficientFundsException when withdrawing more than available balance
  • Test both custom exceptions with appropriate error messages
Sample Code:
// Custom exception classes
public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

public class CustomExceptionPractice {
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 0 || age > 150) {
            throw new InvalidAgeException("Age " + age + " is not valid. Must be between 0 and 150.");
        }
        System.out.println("Age " + age + " is valid");
    }
    
    public static void withdraw(double amount, double balance) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Insufficient funds. Requested: " + amount + ", Available: " + balance);
        }
        System.out.println("Withdrawal successful. New balance: " + (balance - amount));
    }
}

Exercise 4: Multiple Exception Handling

Practice handling multiple exceptions in a single try-catch block.

Requirements:

  • Create a method that can throw multiple types of exceptions
  • Use multiple catch blocks to handle different exception types
  • Use a single catch block with multiple exception types
  • Implement a finally block to perform cleanup operations
  • Demonstrate exception propagation
Sample Code:
public class MultipleExceptionPractice {
    public static void processData(String data, int divisor) {
        try {
            // This can throw multiple exceptions
            int number = Integer.parseInt(data);
            int result = number / divisor;
            System.out.println("Result: " + result);
            
            // Simulate another potential exception
            if (result < 0) {
                throw new IllegalArgumentException("Result cannot be negative");
            }
            
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format");
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Cleanup: Data processing completed");
        }
    }
    
    // Alternative with single catch for multiple exceptions
    public static void processDataAlternative(String data, int divisor) {
        try {
            int number = Integer.parseInt(data);
            int result = number / divisor;
            System.out.println("Result: " + result);
        } catch (NumberFormatException | ArithmeticException e) {
            System.out.println("Error occurred: " + e.getClass().getSimpleName());
        }
    }
}

Exercise 5: File Operations with Exception Handling

Create a comprehensive file management system with proper exception handling.

Requirements:

  • Create a method to copy a file with exception handling
  • Create a method to search for text in a file
  • Create a method to append text to an existing file
  • Handle FileNotFoundException, IOException, and SecurityException
  • Use try-with-resources for all file operations
  • Create a simple file management utility class
Sample Code:
import java.io.*;
import java.nio.file.*;

public class FileManager {
    public static void copyFile(String source, String destination) {
        try (InputStream in = Files.newInputStream(Paths.get(source));
             OutputStream out = Files.newOutputStream(Paths.get(destination))) {
            
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            System.out.println("File copied successfully");
            
        } catch (IOException e) {
            System.out.println("Error copying file: " + e.getMessage());
        }
    }
    
    public static boolean searchInFile(String filename, String searchText) {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
            String line;
            int lineNumber = 1;
            while ((line = reader.readLine()) != null) {
                if (line.contains(searchText)) {
                    System.out.println("Found '" + searchText + "' at line " + lineNumber);
                    return true;
                }
                lineNumber++;
            }
            return false;
        } catch (IOException e) {
            System.out.println("Error searching file: " + e.getMessage());
            return false;
        }
    }
    
    public static void appendToFile(String filename, String text) {
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filename), 
                                                           StandardOpenOption.APPEND, 
                                                           StandardOpenOption.CREATE)) {
            writer.write(text + System.lineSeparator());
            System.out.println("Text appended successfully");
        } catch (IOException e) {
            System.out.println("Error appending to file: " + e.getMessage());
        }
    }
}