0

The below exceptions are coming in while I am trying to read from a file in java.

error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    String inputString = IOUtils.toString(new FileInputStream(FileUtils.getFile(testDirectory,

error: unreported exception IOException; must be caught or declared to be thrown
    String inputString = IOUtils.toString(new FileInputStream(FileUtils.getFile(testDirectory,

The file IOUtil is of the package org.apache.commons.io,the functions have 'throws' in them in the IOUtil file, still these errors are coming.

  • 1
    Those are checked exceptions, meaning you must either `catch` them (with a `try`/`catch` block), or you must declare them in your method signature (`void myExample() throws IOException {...}`). The declaration basically says "I'm not handling this exception, those who call me must handle it instead". The errors you are seeing are _compile-time_ errors, which means your program hasn't been compiled and cannot be run. – Rogue Apr 18 '23 at 16:23

2 Answers2

0

You need to add throws for both FileNotFoundException and IOException.

import java.io.*;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.*;

public class ThrowsExample {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String testDirectory = "test/";
        String inputString = IOUtils.toString(
                new FileInputStream(FileUtils.getFile(testDirectory)),
                StandardCharsets.UTF_8);

        System.out.println(inputString);
    }
}

Method signatures:

+ java.io.FileInputStream.FileInputStream(File file) throws FileNotFoundException

+ String org.apache.commons.io.IOUtils.toString(InputStream input, Charset charset) throws IOException
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

error: unreported exception IOException; must be caught or declared to be thrown

The message here is telling, you have to manage explicitly this exception because this is a checked exception. You have to managed it in a try/catch statement and then return a custom message if needed:

try {

} catch(IOException e) {

}

or sign your method with this exception to indicate to the user of your method that they will have to handle this kind of exception.

public void method() throws IOException {

}
Harry Coder
  • 2,429
  • 2
  • 28
  • 32