This project demonstrates the use of the throws keyword in Java to delegate exception handling. Instead of catching a FileNotFoundException locally, the method declares it in its signature, passing the responsibility of error management to the calling method.
- Task: Create
accessSecretDocument(String documentPath)method. - Mechanism: Use the
throws FileNotFoundExceptiondeclaration in the method signature. - Implementation: Attempt to instantiate a
FileReaderwithout a localtry-catchblock. - Goal: Delegate the potential "file not found" error to the caller.
- Java 8+
The accessSecretDocument method illustrates how checked exceptions work in Java. Since FileNotFoundException is a checked exception, any method attempting to open a file must either handle the exception or declare it using throws. The calling method (main) implements a try-catch block to provide feedback if the specified file path is invalid.
Error: non_existent_file.txt (The system cannot find the file specified)
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Solution {
public static void main(String[] args) {
try {
accessSecretDocument("non_existent_file.txt");
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void accessSecretDocument(String documentPath) throws FileNotFoundException {
FileReader reader = new FileReader(documentPath);
}
}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