Reputation: 61
I have a custom exception class written as
public class MyCustomException extends RuntimeException {
public MyCustomException(Throwable cause) {
super(cause);
}
enter code here
/**
* @param message
* @param cause
*/
public MyCustomException(String message, Throwable cause) {
super(message, cause);
}
}
In my serviceImpl layer
@Override
public List<SiteDetails> getSite() throws MyCustomException {
}
SONAR (Ecplise IDE plugin for linting) states:
Remove the declaration of thrown exception '.MyCustomException' which is a runtime exception
Should I remove the declaration or should I extend Exception
in MyCustomException
class instead of RunTimeException
?
Upvotes: 5
Views: 11496
Reputation: 1259
I had same situation, you have to catch the runtime exception, in my case was an Array Out Of Bound Exception due to I'm parsing a string separated from special char value but sometimes the string value is not corresponding to the right convention, right? So I must handle it, but Sonar was blaming me for the same reason! ArrayIndexOutOfBoundsException is derived from runtime exception , anyway once you know that your block of code could retrieve some runtime exception, instead of throw it directly, use a catch block and into this just throw your custom exception.
catch (ArrayIndexOutOfBoundsException e) {
throw new YourCustomException("your message",e);
}
In this way you can remove the throws signature on your method, and Sonar will be happy
Upvotes: 0
Reputation: 131346
The sonar issue is very very primarily opinion based.
A RuntimeException
is not forced to be handled and so declared but it is not a bad practice to declare it in a method to document this case.
Should I remove the declaration or should I extend Exception in MyCustomException class instead of RuntimeException
If you deem that MyCustomException
is an exception that has to be necessarily handled by the client, MyCustomException
should derive from Exception
rather thanRuntimeException
.
Otherwise if the exception cannot be handled by the client in most of circumstances, you should remove the declaration to make Sonar Happy or mark (at least trying) this issue as a false positive if you think that it makes sense to convey the exception even if it is a RuntimeException
.
Upvotes: 6