Reputation: 166
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?)
Upvotes: 2
Views: 2247
Reputation:
I would just pass the throwing class into the constructor, like this:
public class InitializationException extends Exception {
public InitializationException(Class<?> throwingClass) { ... }
...
}
Upvotes: 1
Reputation: 424983
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!");
}
}
Upvotes: 0
Reputation: 41
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);
Upvotes: 1
Reputation: 4640
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()
}
Upvotes: 0
Reputation: 47699
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).)
Upvotes: 1
Reputation: 13374
Look at Throwable.getStackTrace()
. Each StackTraceElement
has getClassName()
. You can look at element [0]
to determine the origination of the exception.
Upvotes: 7