Link to home
Start Free TrialLog in
Avatar of srikotesh
srikotesh

asked on

Public methods should throw at most one checked exception how to avoid this in java

Hi Experts,

We used Sonar tool  to analyse our Java code and it has this rule
Public methods should throw at most one checked exception(major issue)
how to avoid it
public void delete() throws IOException, PPException {      
  /* ... */
}

PPException extends Exception

i have to use try catch blocks to avoid this or is there any alternative is there.
Avatar of dpearson
dpearson

You'd need to show us the code inside delete() to get any real help here.

As a trivial workaround you can also modify the signature to be:
public void delete() throws Exception {
}

but that's not really addressing the underlining issue.

Doug
ASKER CERTIFIED SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yeah CPCOlin makes a good point - that's something of a weird coding guideline coming from Sonar.

But people's opinions on checked exceptions can be a bit "sensitive".

That does raise another option - which is converting the checked exception to unchecked.  Personally I hate that (I think checked exceptions are good), but others think it's cool.

If you wish to do it, it's easy:

public void delete() {
  try {
     // Current Code
  } catch (Exception ex) {
     // This is a RuntimeException - so no need to declare it in the signature
     throw new IllegalStateException("Something bad happened",ex) ;
  }
}

Doug
Since Java 7, though, you shouldn't catch Exception in places where you can multi-catch the specific exception types.
Since Java 7, though, you shouldn't catch Exception in places where you can multi-catch the specific exception types.

True - but not sure that wouldn't be muddying this particular pool a little further :)

Doug
In a question that starts with the asker trying to make a chunk of code cleaner and use better practices, I'll always offer advice that errs on the side of cleanliness.
Avatar of srikotesh

ASKER

Excellent