我想知道这是否是一个好习惯,将throw封装在方法中,然后在return方法中调用
int returnMethod(){
if(ok){
return 1;
}
alwaysReturnRuntimeException();
return 1; //Fake
}
void alwaysReturnRuntimeException(){
if(specificError){
throw new OneRuntimeException();
}
// General error
throw new GeneralRuntimeException();
}
或者最好生成异常,但是不要抛出。仅将其返回并扔到父方法上。
int returnMethod(){
if(ok){
return 1;
}
throw buildException();
}
void buildException(){
if(specificError){
return new OneRuntimeException();
}
// General error
return GeneralRuntimeException();
}
答案 0 :(得分:2)
我想说一种决定必须抛出哪种异常的方法是重用代码的有效方法,但前提是它确实适合您的应用程序设计(无需知道其他有关代码的更多详细信息,我可以请给出有充分根据的选择)。但是,我强烈建议您不要在代码中使用未经检查的异常(但这是另一回事,而且有点主观)。
两个建议,以防您确实需要此方法:
throwMyException()
(alwaysReturnRuntimeException()
对于不返回任何内容的方法来说是一个坏名字)您的代码可能是这样的:
int returnMethod(){
if(!ok){
throwRuntimeException();
}
return 1;
}
void throwRuntimeException() throws OneRuntimeException, GeneralRuntimeException {
if(specificError){
throw new OneRuntimeException();
}
// General error
throw new GeneralRuntimeException();
}