"Unhandled exception: java.io.IOException" compile time error: What exactly is it for?

1.1k Views Asked by At

Consider the following snippet of an unfinished method:

private void synchronize(TreeItem<String> treeItem, Path newDir) {
    for (TreeItem<String> i : treeItem.getChildren()) {
        if (i.getGraphic().equals(GREEN_DOT)) {
            copyFile(new File(i.getValue()), newDir.toFile(), DEFAULT_COPY_BUFFER_SIZE);
        }
    }
}

In my project, the copyFile() call is underlined and the IDE displays the error described above. I understand what an exception is, but what I'm not so sure about is why does this particular error needs to be fixed by adding "throws IOException" into the method signature. Why does it need to be there; isn't throwing the exception within the implementation of copyFile() enough? What is the utility gained by typing that little formula into the method signature, an propagating it like that into any method that calls another method with it already written in?

3

There are 3 best solutions below

0
HTNW On BEST ANSWER

You need to declare that your method can throw IOExceptions, so that calling code knows that it may come up. The methods called within your method declare throws IOException, so the compiler knows that an IOException may be thrown within them and interrupt your method, and therefore you must also declare that you can throw IOException as your method can also interrupt calling code. The other way to stop the error is to actually catch the exceptions.

2
Daniel Amieva On

Nope , all methods to work with files need to throws IOexception.

0
yonilx On

Java language specification demands it. The reason could be for better documentation built in, or that the programmer will always remember to deal with these exception.

As you know this is not mandatory as other languages don't require this kind of declaration, but Java does.