This project demonstrates the propagation of multiple related exceptions using the throws keyword. It simulates a data pipeline component that reads the first line of a file, delegating both FileNotFoundException and IOException handling to the calling environment.
- Task: Create
extractFirstLineFromData(String dataFile)method. - Mechanism: Use
throws FileNotFoundException, IOExceptionin the method signature. - Implementation: Utilize
FileReaderandBufferedReaderto access file content without localtry-catchblocks. - Goal: Successfully propagate specific and general I/O errors to the
mainmethod.
- Java 8+
The extractFirstLineFromData method is designed to perform a specific I/O task. By declaring multiple exceptions, it informs the caller about the specific risks involved (missing file vs. general read error). The main method catches these exceptions to ensure the application provides feedback instead of crashing.
Data Error: data_source.txt (The system cannot find the file specified)
Project Structure:
src/com/yurii/pavlenko/
βββ Solution.java
Code
package com.yurii.pavlenko;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Solution {
public static void main(String[] args) {
try {
extractFirstLineFromData("data_source.txt");
} catch (FileNotFoundException e) {
System.out.println("Data Error: File not found - " + e.getMessage());
} catch (IOException e) {
System.out.println("System Error: An I/O failure occurred - " + e.getMessage());
}
}
public static void extractFirstLineFromData(String dataFile) throws FileNotFoundException, IOException {
FileReader fileReader = new FileReader(dataFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String firstLine = bufferedReader.readLine();
System.out.println("First line: " + firstLine);
bufferedReader.close();
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT