The exception of common technical debt processing in Java code

Source: Internet
Author: User

Write in front

Exception handling is a common process in code, in this paper, according to Sonarqube in the exception of the rules and common check results, select the common exception handling of the technical debt, promote the least technical debt coding method.

Exception handlers should preserve the original exceptions

Either log or rethrow this exception.

When handling a caught exception, the original exception ' s message and stack trace should is logged or passed forward.
noncompliant CODE EXAMPLE

 // Noncompliant - exception is losttry... */ } catch (Exception e) { LOGGER.info("context"); }   // Noncompliant - exception is lost (only message is preserved)       try... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }   try... */ } catch (Exception e) { throw new RuntimeException("context"); }

Compliant solution

try... */ } catch (Exception e) { LOGGER.info(e); }   try... */ } catch (Exception e) { throw new RuntimeException(e); }try {  ... */} catch (RuntimeException e) {  doSomething();  throw e;} catch (Exception e) {  // Conversion into unchecked exception is also allowed  throw new RuntimeException(e);}

Error instance:

 protected int AnalyzeJobStep1(String jobName) {Try{Notifybhandler ();returnANALYZEJOBSTEP2 (JobName)}Catch(Exception e)        {Logger.error (E.getmessage (); }return 0; To resolve the instance:protected int AnalyzeJobStep1(String jobName) {intnret=0;Try{Notifybhandler ();        Nret = ANALYZEJOBSTEP2 (jobName); }Catch(Exception e) {Logger.error ("Notifybhandler Trigger Exception", e); }returnNret; }
Don ' t directly use Exception and RuntimeException

Sonarrule:generic exceptions should never be thrown (squid:s00112)
Using such generic exceptions as Error, RuntimeException, Throwable, and Exception prevents calling methods from handling True, system-generated exceptions differently than application-generated errors.
noncompliant Code Example

publicvoidfoothrows Throwable {  // Noncompliant  thrownew RuntimeException("My Message");     // Noncompliant}

Compliant solution

publicvoidfoo(String bar) {  thrownew MyOwnRuntimeException("My Message"); }

Another related rule:generic exceptions should never be thrown
The below should be avoided.

@Overridepublic void myMethod() throws Exception {...}

Define and throw a dedicated exception instead of using a generic one.

Exceptions should not being thrown in finally blocks
try {  /* some work which end up throwing an exception */  thrownewfinally {  /* clean up */  thrownew RuntimeException();       // Noncompliant; will mask the IllegalArgumentException}

Compliant solution

try {  /* some work which end up throwing an exception */  thrownewfinally {  /* clean up */                                         // Compliant}
Checked exceptions should not be thrown

The purpose of checked exceptions is to ensure that errors would be dealt with, either by propagating them or by handling T Hem, but some believe it checked exceptions negatively impact the readability of source code, by spreading this error ha Ndling/propagation logic everywhere.
This rule verifies, that no method throws a new checked exception.

CODE EXAMPLE
public void myMethod1() throws CheckedException {  ...  throw new CheckedException(message);   // Noncompliant  ...  throw new IllegalArgumentException(message); // Compliant; IllegalArgumentException is unchecked}   
Solution Example
publicvoidmyMethod2throws CheckedException {  // Compliant; propagation allowed  myMethod1();}
Public methods should throw at the most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. Throwing exceptions makes them fully part of the The method.
But to keep the complexity for callers reasonable, methods should no throw more than one kind of checked exception.

noncompliant CODE EXAMPLE
public void delete() throws IOException, SQLException {      // Noncompliant  ... */}
Compliant solution
public void delete() throws SomeApplicationLevelException {  ... */}

The exception of common technical debt processing in Java code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.