Q:

java return type error and error handling

I am a newbie. One methods has two errors. Please help to resolve these.
I am making file system using multi node tree.
This method returns a file/directory of given name in a subdirectory. After looping, if it doesn't have such file/directory, it should give an error.
import java.util.ArrayList;
import java.util.Arrays;
import driver.exception.InvalidFileDirectoryException;

public class FileNode {

    private FileNode parent;
    private ArrayList<FileNode> children = new ArrayList<FileNode>();
    private String name;

    public FileNode getChild(String name) {   // This method must return a type of FileNode.
        for (int i = 0; i < children.size(); i++) {
                if (children.get(i).getName() == name) {
                    return children.get(i);
                }
                if ((i == children.size()-1) 
                    && (children.get(i).getName() != name)) {
                    throw new InvalidFileDirectoryException(
                        name + ": No such file or directory");   // Unhandled exception type InvalidFileDirectoryException
                }
        }
    }

I can understand the first error. This method can return nothing if there is no such file or directory. However, I want to give an error message in that case. What should I do? Please help!
public class InvalidFileDirectoryException extends Exception {

    public InvalidFileDirectoryException() {
        super();
    }

    public InvalidFileDirectoryException(String message) {
        super(message);
    }
}

A:

Change your getChild method to:-
public FileNode getChild(String name) throws InvalidFileDirectoryException {
    for (int i = 0; i < children.size(); i++) {
        if (children.get(i).getName().equals(name)) {
            return children.get(i);
        }
    }
    throw new InvalidFileDirectoryException(name + ": No such file or directory");
}

This will scan through the children collection. If a match is found, the child will be returned from this method. If the loop completed and no match was found, it will throw the exception. Notice the method signature says throws InvalidFileDirectoryException.

