SonarQube error - Throwing a dedicated exception instead of generic exception for an Abstract class

I am cleaning up SonarQube issues, and one of the errors complains: Define and throw a dedicated exception instead of using a generic one.

public abstract class Message {

    public abstract byte[] getPayload() throws Exception;

    public abstract Optional<String> getStringMessage() throws Exception;


Since this is a class from the library that people use as an API, and an abstract class that people inherit, I'm not sure if changing this to throw a dedicated exception would impact other services and thus, not okay. Any advice, direction, answer would be greatly appreciated!

- - Source


answered 1 week ago LppEdd #1

Do not change the thrown Exception before having checked which Exceptions are thrown by Message's extending types. You might break existing code (see below).

If every extending type did not use a more specific Exception, then, you have to replace it with a clearer & more idiomatic one.

A custom Exception can carry additional data as class fields. This additional data can be set at throwing point (which is usually where that data is available only), and inspected at upper levels, when handled.

Being that this class acts as a sort-of interface (consider refactoring it to an interface, indeed), it will be the one exposed/used everywhere, and thus it needs to be as clear as possible.

A couple possible names might be


Applying a more specific Exception, having extending types which already provide specific ones, or even just the base Exception, will result in compile errors

Starting point

enter image description here

Now, upgrade the Exception to a "custom" one. Error!

enter image description here

So be careful, or you'll have people complaining.

comments powered by Disqus