在 java 中抛出异常重构

throws Exception refactoring in java

我正在更改我的代码

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

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

    return user;
}

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();
    }
}

实施 2 给出了用户可能未初始化的编译错误,有人可以帮助我在这里缺少什么,对我来说似乎很奇怪。

编译器不知道SomeHandlerInProject.throwCustomErr()总是抛出异常,所以就编译器代码分析而言,该方法可能return正常。

如果是,user 的值是多少?它没有值,所以编译器会抱怨它,因为它应该这样做。请记住,class SomeHandlerInProject 可以更改为不抛出异常,而不必使用 getUser() 方法重新编译 class,因此编译器抱怨它是正确的。

即使知道这个方法总是会抛出异常,你还是要写代码就好像它不会抛出异常一样,所以你必须给[=赋值12=],通过初始化它,或者在 catch 块中分配给它。

如果目标是共享构建异常所需的逻辑,您应该使辅助方法 return 成为异常,而不是抛出它,让调用者执行 throw。这样编译器就不会报错了:

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();
    }
}

堆栈跟踪保持不变,因为它是为调用堆栈快照的构造函数位置。