简体   繁体   中英

Java: unhandled exception

I would like to handle an exception but the Eclipse editor is giving me tips which I'm not understanding. This is the method's code:

    public Collection<String> listOfFriends(String codePerson)
            throws NoSuchCodeException {

        Collection<String> s = new LinkedList<>();
        try {
            people.get(codePerson).getFriendsCodes().forEach( code -> s.add(getPerson(code)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;

Where getPerson is:

    public String getPerson(String code) throws NoSuchCodeException {
        if(!people.containsKey(code)){
            throw new NoSuchCodeException();
        }
        return people.get(code).getCode() + " " + people.get(code).getName() + " " + people.get(code).getSurname();

and the exception is:

public class NoSuchCodeException extends Exception {
    NoSuchCodeException(){}
    NoSuchCodeException(String msg){
        super(msg);
    }

}

Eclipse returns two errors in the listOfFriends method, one where getPerson() is invoked, saying "Unhandled exception type NoSuchCodeException" and the other one in the catch row, saying "Unreacheable catch block for NoSuchCodeException. This exception is never thrown from the try statement body".

PS: I added try and catch in the listOfFriends method just to try to solve the problem, since, as far as I know, given that the method has in its declaration "throws NoSuchCodeException", it shouldn't be obligatory, right?

Thanks in advance.

The issue is caused by the lambda function. The interface of the function that forEach requires doesn't declare any kind of checked exceptions: take a look at java.util.function.Consumer . That's the place where the first issue occurs, the second one is simply a result of the first one.

Either you should make NoSuchCodeException extend RuntimeException or add a try catch block to you lambda. I would suggest you to stick to the first solution, unless NoSuchCodeException is something that may occur under normal conditions.

Also take a look at this question: Java: checked vs unchecked exception explanation .

You're going to have to catch that exception inside of the forEach block. Since forEach isn't declared to handle exceptions, you have to help it along the way.

The alternative is to change your exception into an unchecked exception, but that may not work for your particular use case.

try {
    people.get(codePerson).getFriendsCodes().forEach(code -> {
        try {
            s.add(getPerson(code));
        } catch (NoSuchCodeException e) {
            e.printStackTrace();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM