[英]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()
总是抛出异常,所以就编译器代码分析而言,该方法可能会正常返回。
如果是这样, user
的价值是什么? 它没有值,所以编译器会抱怨它,因为它应该。 请记住,类SomeHandlerInProject
可以更改为不抛出异常,而不必使用getUser()
方法重新编译该类,因此编译器抱怨它是正确的。
即使您知道该方法总是会抛出异常,您仍然必须编写代码,就好像它不会一样,因此您必须为user
赋值,或者通过初始化它,或者通过在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();
}
}
堆栈跟踪保持不变,因为它是为调用堆栈快照的构造函数位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.