If my class already extends some other class, what should I do if I want an instance of my class to be thrown as an Exception object?
The only method I found is that some superclass must be extending Exception class. Is there any other way? EDIT: Also does this indicate a design flaw, if yes then please explain how What is the right way to use a custom exception in your class, Is it by adding a reference of the custom Exception in your class OR calling 'new' whenever you require it, Can you give a code outline?
You will have to wrap it in another class. In java you can only throw subtypes of Throwable, which is a class.
Example:
public class Wrapper extends Exception {
public final MyClass wrapped;
public Wrapper(MyClass toWrap) { wrapped = toWrap; }
}
If this is an application of the trampoline technique, or similiar control flow techniques, then there are ways to not get a stack trace (reducing the time it takes to create the object). I can look it up if need be.
A Way out could be Define your class with generics to take Exception as parameter. This way you will be able to make other feel that in some sense this is exception.
public class One{}
public class Two<E extends Exception> extends One {
E e = null;
public void throwE() throws E {
throw e;
}
}
PS Note: I have already assumed that you know that it is not possible since you will have to extends Exception class for that purpose
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With