1

I would like to override toString() method of several personnal exceptions which are of type Exception or RuntimeException.

Say that I would like to display test with toString() methods for both Exception and RuntimeException sub-classes. I have to override toString() one time only so.

How can I do it because Java doesn't support multi inheritance please ? I just don't want to write 2 times toString() method for both type of exceptions...

Example :

public class SubClassOfException extends Exception {

    ...

   @Override
   public String toString() {   
      return "test";
   }

}

My goal is to create SubClassOfRuntimeException and benefit of the custom toString() method of SubClassOfException because RuntimeException is a sub-class of Exception.

Is there a way to do it or I have to duplicate toString() code into SubClassOfException and SubClassOfRuntimeException ?

1 Answer 1

4

Since your SubClassOfException is hierarchical on the same level as RuntimeException, you cannot share the toString() method via inheritance.

But you don't need to duplicate the code either, if both toString() methods in your concrete exception types delegate the actual string building to a common "exception string builder". I mean something like

class ExceptionPrinter {
    public static String exceptionToString(Exception e) { ... }
}

and in both exception classes

@Override
public String toString() {
    return ExceptionPrinter.exceptionToString(this);
}
Sign up to request clarification or add additional context in comments.

3 Comments

yep I did that but I would have find another way with inheritance but if it's not possible I will do that, thx ;)
I see, but unfortunately it's not possible, because inheritance can only work up- or (to be precise) downwards, never horizontal.
hmm thank you to notice that. It's logical but I didn't know this "rule"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.