The catch
block of a checked exception "E" may be hidden because the corresponding try
block only throws exceptions
derived from E.
These derived exceptions are handled in dedicated catch
blocks prior to the catch
block of the base exception E.
The catch
block of E is unreachable and should be considered dead code. It should be removed, or the entire try-catch structure should
be refactored.
public class HiddenCatchBlock { public static class CustomException extends Exception { } public static class CustomDerivedException extends CustomException { } public static void main(String[] args) { try { throwCustomDerivedException(); } catch(CustomDerivedException e) { // ... } catch(CustomException e) { // Noncompliant; this code is unreachable // ... } } private static void throwCustomDerivedException() throws CustomDerivedException { throw new CustomDerivedException(); } }
public class HiddenCatchBlock { public static class CustomException extends Exception { } public static class CustomDerivedException extends CustomException { } public static void main(String[] args) { try { throwCustomDerivedException(); } catch(CustomDerivedException e) { // Compliant; try-catch block is "catching" only the Exception that can be thrown in the "try" //... } } }