Catch and handle specifically-thrown exceptions. Catching generic exceptions might hide issues when specific exceptions are thrown.
1public void exceptionHandlingNoncompliant() {
2 // Noncompliant: catch block handles generic Exception, but not SomeException.
3 try {
4 doSomething();
5 throw new SomeException();
6 } catch (IndexOutOfBoundsException e) {
7 log.error(e.getMessage());
8 } catch (Exception e) {
9 log.error(e.getMessage());
10 }
11}
1public void exceptionHandlingCompliant() {
2 // Compliant: catch block handles SomeException.
3 try {
4 doSomething();
5 throw new SomeException();
6 } catch (IndexOutOfBoundsException e) {
7 log.error(e.getMessage());
8 } catch (SomeException e) {
9 log.error(e.getMessage());
10 } catch (Exception e) {
11 log.error(e.getMessage());
12 }
13}