1

I have a list of exceptions (with package name path: com.a.b.ExceptionA) and error codes map.

Now, user will call new ApiException(errorcode,"message"), or new ApiException(errorcode,"message", Throwable t). Then, inside BaseException, I want to create ExceptionA,B based upon errorcode and throw it.

I can look up the map and get the exception type path, but how to create the exception and throw it? So some thing like below? or any better approach?

Class<?> c = Class.forName("com.a.b.ExceptionA");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("message");
throw object;

Thanks!

Santhosh
  • 885
  • 1
  • 9
  • 15
  • No, here the objective iam inquiring is to create exception object dynamically based upon the error code type and then throw it based upon passed in arguments. – Santhosh Nov 16 '15 at 03:21
  • The approach looks correct. But since you can't throw an Object, cast it to Throwable before throwing. – Simon DeWolf Nov 16 '15 at 03:24
  • Not sure, why it is marked as duplicate? – Santhosh Nov 16 '15 at 05:10
  • With this approach, we create two objects(ApiException and IndividualException say ExceptionA), but i want to create one object and throw that based upon error code passed. – Santhosh Nov 16 '15 at 11:12

0 Answers0