Why you should care
Although this is sometimes unavailable, nesting try/catch blocks severely impacts the readability of the source code as it makes it difficult to understand which block will catch which exception.
How we detect
CAST Highlight counts one occurrence each time a try block contains one or more nested other try.
Bad CodeÂ
try { // some stuff // .... if (toto) { try { // ===> VIOLATION // another stuff // ... } catch (Exception e) { throw e; } } } catch (Exception e) { throw e; }
Good CodeÂ
try { // some stuff // .... } catch (Exception e) { throw e; } if (toto) { try { // another stuff // ... } catch (Exception e) { throw e; } }
References
https://softwareengineering.stackexchange.com/questions/118788/is-using-nested-try-catch-blocks-an-anti-pattern
https://rules.sonarsource.com/java/RSPEC-1141
https://rules.sonarsource.com/java/RSPEC-1141
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.