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

Sargon1

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?

HTNW

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related