Search code examples
javaexceptioncustom-exceptions

Java - how to overwrite getMessage() for custom checked and unchecked exceptions using one implementation?


How to have MyException and MyRuntimeException use the same custom getMessage() implementation?

As Java does not come with multiple inheritance I don't know what to do. At the moment I have duplicate code in both classes...

Important detail: getMessage() does stuff like this.class.getName(). So I do need getMessage() to use reflections cause i need the classname of the object for localization.

So either I need a solution for my first question or a solution on how to use reflections within static methods cause then I could use some utility class which both exceptions could use?

One solution might be a static method in some helper class and then using this:

return new Object() { }.getClass().getEnclosingClass().getEnclosingClass();

Isn't it?


Solution

  • Try making a static shared helper function to implement your custom getMessage:

    class MyException extends Exception {
        ....
        public String getMessage() {
            return ExceptionHelper.getMessage(this);
        }
    }
    
    class MyRuntimeException extends RuntimeException {
        ....
        public String getMessage() {
            return ExceptionHelper.getMessage(this);
        }
    }
    
    class ExceptionHelper {
        public static String getMessage(Exception e) {
            // your shared impl here
        }
    }
    

    Edit - if your Exception subclasses have more than just an impl of getMessage copy-pasted between them, you may want to share that as well. A slight tweak of the above to turn the static helper into an encapsulated class will handle this well.

    For example: create a class named something like ExceptionDetails, where this shared code and variables (and any other duplication) could live, and each Exception subclass would have their own instance of ExceptionDetails.