I have created Exception xml and dynamically create and throw exception.
<exception-mappings>
<exception-mapping key="exceptionkey1">
<class-name>com.package.CheckedException</class-name>
<message>Checked Exception Message</message>
</exception-mapping>
<exception-mapping key="exceptionkey2">
<class-name>com.package.UnCheckedException</class-name>
<message>UnChecked Exception Message</message>
</exception-mapping>
I create object of exception dynamically using reflection depending on the exception key.
public static void throwException(final String key) throws CheckedException, UncheckedException {
ExceptionMapping exceptionMapping = exceptionMappings.getExceptionMappings().get(key);
if (exceptionMapping != null) {
try {
Class exceptionClass = Class.forName(exceptionMapping.getClassName());
try {
throw ()exceptionClass.newInstance(); // line X
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I want to know which class to typecast at line X so that I do not need to use If/else. Reason behind I do not want to use if else is, it may be possible that in future, there may be new classes added and I do not want to change this code every time new exception is added.
My base logic is my service layer will throw either CheckedException or UncheckedException. If CheckedException is thrown, it will be handled by my web layer. Also I can not throw Super parent class Exception or Throwable as my web layer only catch CheckedException. If UncheckedException is thrown, it will display exception page.
Please help me as I am not able to proceed further.
EDIT: Any other solution is also accepted.
Well, in the name of science, here's how you can do it. Would I recommend doing this? By no means. Would I ever do anything remotely like this myself? Probably not.
public class ExceptionFactory {
public static void throwException(String className)
throws CheckedException, UncheckedException {
Class<?> exceptionClass;
try {
exceptionClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
try {
if (CheckedException.class.isAssignableFrom(exceptionClass)) {
throw exceptionClass.asSubclass(CheckedException.class)
.newInstance();
} else if (UncheckedException.class
.isAssignableFrom(exceptionClass)) {
throw exceptionClass.asSubclass(UncheckedException.class)
.newInstance();
} else {
throw new IllegalArgumentException(
"Not a valid exception type: "
+ exceptionClass.getName());
}
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
public static void main(String... args) {
try {
throwException("CheckedException");
} catch (CheckedException e) {
System.out.println(e);
} catch (UncheckedException e) {
System.out.println(e);
}
}
}
class CheckedException extends Exception {
}
class UncheckedException extends Exception {
}