Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to rethrow a wrapped Exception

843810Nov 9 2009 — edited Nov 9 2009
I'm using an API that wraps all the exceptions into one custom exception. So far so good. However, I want to rethrow the wrapped exceptions so my code can handle them separately. One approach would be:
catch (APIException e) {
	Throwable cause = e.getCause();
	if (cause instanceof MyException1) {
		throw (MyException1)cause;
	}
	else 	if (cause instanceof MyException2) {
		throw (MyException2)cause;
	}
}
Is there a way to do this more intelligently? I was trying something with Generics, but couldn't find the right syntax. Somehting like:
catch (APIException e) {
	Throwable cause = e.getCause();
	Class<? extends Throwable> exceptionClass = cause.getClass();
	throw exceptionClass.cast(cause); //doesn't quite work
}
Edited by: andrers2b on Nov 9, 2009 3:39 PM

Edited by: andrers2b on Nov 9, 2009 3:41 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 7 2009
Added on Nov 9 2009
4 comments
942 views