在retun方法上封装运行时异常,还是生成异常方法?

时间:2019-02-07 12:28:33

标签: java exception methods return

我想知道这是否是一个好习惯,将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();
}

1 个答案:

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