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?)

有帮助吗?

解决方案

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

其他提示

Something like:

StackTraceElement[] trace = theException.getStackTrace();
String className = trace[0].getClassName();

(Though I'm not quite sure whether you want the first element or the last in the trace.)

(And note that you can create a Throwable and do getStackTrace() on it, without ever throwing it, to find out who called you (which would be trace element 1).)

class InitializationException extends Exception {
    private final String classname;
    InitializationException(String msg, Object origin) {
        super(msg);
        this.classname = origin != null ? origin.getClass().toString() : null;
    }
    public String getClassname() {
        return this.classname;
    }
}

. . . . throw new InitializationException("Something went wrong", this);

I would just pass the throwing class into the constructor, like this:

public class InitializationException extends Exception {

    public InitializationException(Class<?> throwingClass) { ... }

    ...
}

Its a workaround:

you could pass the classname within the Constructor, something like

throw new  InitializationException(getClass().getName());

or may be call the class like

throw new InitializationException(this);

and handle the name extraction in your excpetin class

 InitializationExcpetion(Object context){ 
this.name = getClass().getName() 
}

The answer is you force the class throwing the exception to tell the exception which class it is:

public class InitializationException extends Exception {

    public InitializationException(Class<?> c) {
        super( "The class " + c.getName()+ " had not been initialized properly!");
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top