简体   繁体   中英

throws Exception refactoring in java

I am changing my code from

Implementation 1 : 
public User getUser(String userid) {
    User user;
    try {
        // some code to get User

    }catch(InterruptedException e) {
        throw new CustomException();
    }

    return user;
}

to

Implementation 2 : 
public User getUser(String userid) {
    User user;

    try {
        // some code to get User

    }catch(InterruptedException e) {
        SomeHandlerInProject.throwCustomErr();
    }

    return user;
}


class SomeHandlerInProject {
    public static void throwCustomErr() {
        throw new CustomException();
    }
}

Implementation 2 gives compilation error that user might not be initialized, can someone help what am I missing here, seems very weird to me.

Compiler doesn't know that SomeHandlerInProject.throwCustomErr() always throws an exception, so as far as the compilers code analysis goes, the method may return normally.

If it does, what would the value of user be? It wouldn't have a value, so the compiler complains about that, as it should. Remember, the class SomeHandlerInProject could be changed to not throw exception, without having to recompile the class with the getUser() method, so the compiler is correct to complain about it.

Even though you know the method always throws an exception, you still have to write the code as-if it doesn't, so you must assign a value to user , either by initializing it, or by assigning to it in the catch block.

If the goal is to share the logic needed to build the exception, you should make the helper method return the exception, not throw it, and let the caller do the throw . That way the compiler won't complain:

public User getUser(String userid) {
    User user;
    try {
        // some code to get User
    } catch (InterruptedException e) {
        throw SomeHandlerInProject.buildCustomErr();
    }
    return user;
}

class SomeHandlerInProject {
    public static CustomException buildCustomErr() {
        return new CustomException();
    }
}

The stacktrace remains the same, since it is the constructor location that is snapshot'd for the call stack.

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