리팩토링(스프링기반)

동일 처리를 하는 catch문 합치기

까오기 2019. 1. 8. 16:41

Combine this catch with the one at line 82, which has the same body.


동일 처리를 하는 catch문 합치기 

수정 전

public boolean checkUser(UserParam userParam) {

try {

if(getUserInfo(userParam) != null) return true;

}catch(DataNotFoundException e) {

return false;

}catch(UserNotFoundException e) {

return false;

}

return false;

}

수정 후

public boolean checkUser(UserParam userParam) {

try {

if(getUserInfo(userParam) != null) return true;

}catch(DataNotFoundException | UserNotFoundException  e) {

return false;

}

return false;

}


Catches should be combined (squid:S2147)

CODE_SMELL Code smell MINOR Minor

Since Java 7 it has been possible to catch multiple exceptions at once. Therefore, when multiple catch blocks have the same code, they should be combined for better readability.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

catch (IOException e) {
  doCleanup();
  logger.log(e);
}
catch (SQLException e) {  // Noncompliant
  doCleanup();
  logger.log(e);
}
catch (TimeoutException e) {  // Compliant; block contents are different
  doCleanup();
  throw e;
}

Compliant Solution

catch (IOException|SQLException e) {
  doCleanup();
  logger.log(e);
}
catch (TimeoutException e) {
  doCleanup();
  throw e;
}