Search code examples
javacustom-exceptions

How can I get the name of the class that throws a custom made Exception


I'm preparing a project for college where I need to write a custom made exception that will be thrown by a couple of classes in the same package when they were not initialized properly. The problem is that I must let the user know which of those classes wasn't initialized properly (and throwed the exception)... So I was thinking about something like this:

class InitializationException extends Exception {

private static final String DEFAULT_MSG =
            "This " + CLASSNAME-THROWINGME + " had not been initialized properly!";

    protected String msg;

InitializationException() {
    this.msg = DEFAULT_MSG;
}

    InitializationException(String msg) {
    this.msg = msg;
}
}

(btw, can it be achieved via reflection?)


Solution

  • Look at Throwable.getStackTrace(). Each StackTraceElement has getClassName(). You can look at element [0] to determine the origination of the exception.