简体   繁体   English

在java中抛出异常重构

[英]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.实现 2 给出了用户可能未初始化的编译错误,有人可以帮助我在这里缺少什么,对我来说似乎很奇怪。

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.编译器并不知道SomeHandlerInProject.throwCustomErr()总是抛出异常,所以就编译器代码分析而言,该方法可能会正常返回。

If it does, what would the value of user be?如果是这样, user的价值是什么? 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.请记住,类SomeHandlerInProject可以更改为不抛出异常,而不必使用getUser()方法重新编译该类,因此编译器抱怨它是正确的。

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.即使知道该方法总是会抛出异常,您仍然必须编写代码,就好像它不会一样,因此您必须为user赋值,或者通过初始化它,或者通过在catch块中为其赋值。

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 .如果目标是共享构建异常所需的逻辑,您应该让辅助方法return异常,而不是抛出异常,并让调用者执行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.堆栈跟踪保持不变,因为它是为调用堆栈快照的构造函数位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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