Sonarqube - avoiding catch generic Exception

风格不统一 提交于 2021-01-28 11:21:11

问题


Sonar complains when catching the generic type Exception, but sometimes we need to do some general exception handling for ALL (even not yet recognized) exception types. What is the solution to pass this sonar check?


回答1:


Unless you are invoking a method which throws Exception, there is no need to catch Exception: catch the exceptions you know about, and the compiler will tell you when you have to start handling another one.

The problem with catching "not yet recognized" Exceptions is that you lose the signal that you have to handle a new exception in a special way.

For example:

void someMethod() {
  // Do stuff.
}

void callIt() {
  try {
    someMethod();
  } catch (Exception e) {
    // ...
  }
}

If someMethod is now changed so that it throws, say, an InterruptedException:

void someMethod() throws InterruptedException {
  Thread.sleep(1000);
  // Do stuff.
}

you aren't told by the compiler that you need to add handling for the InterruptedException in callIt(), so you will silently swallow interruptions, which may be a source of problems.

If, instead, you had caught RuntimeException, or RuntimeException | IOException | OtherExceptionYouAlreadyKnowAbout, the compiler would flag that you had to change your code to handle that InterruptedException as well; or, that you can't change the signature of someMethod(), and the checked exception has to be handled there.



来源:https://stackoverflow.com/questions/49065496/sonarqube-avoiding-catch-generic-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!