How do you throw an instance of the Exception class created by reflection?

I am trying to create a function that throws an exception based on the type you are passing.

private void myFunc(Class<?> exceptionType) { ...do some work... throw new exceptionOfTypeExceptionTypePassedIn(newMessage); } 

Can you do it?

+5
source share
2 answers

First, the throw statement only works with Throwable reference expressions or its subtypes. Therefore, the expression you pass to your throw must be of this type. You can achieve this by providing a binding to the exceptionType parameter.

 private void myFunc(Class<? extends Throwable> exceptionType) { 

If you now want to restrict the type of the Throwable subtype, you can also do this.

If this is an Exception , you will need a throws declaration

 private void myFunc(Class<? extends Exception> exceptionType) throws Exception { 

If he has a RuntimeException , he will not

 private void myFunc(Class<? extends RuntimeException> exceptionType) { 

Depending on what you need, you can make a general method. Then it will look like

 private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T { 

Regarding the logic of real reflection, you make the assumption that the corresponding type has an accessible constructor that takes a String argument. If this does not happen, Java will throw all kinds of exceptions. You need to process them.

A potential solution would look like this ( javadoc for Class#getConstructor , javadoc for Constructor#newInstance )

 private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T { final String message = "some message"; try { throw exceptionType.getConstructor(String.class).newInstance(message); } catch (InstantiationException e) { e.printStackTrace(); // rethrow } catch (IllegalAccessException e) { e.printStackTrace(); // rethrow } catch (IllegalArgumentException e) { e.printStackTrace(); // rethrow } catch (InvocationTargetException e) { e.printStackTrace(); // rethrow } catch (NoSuchMethodException e) { e.printStackTrace(); // rethrow } catch (SecurityException e) { e.printStackTrace(); // rethrow } } 

Obviously, you can collapse all of these exception types into a multiple catch statement.

Please note that if the type of exception you passed was one of those specified in existing catch statements, it will be swallowed, i.e. not cast. You can also add all those specified in the throws declaration.

 private static <T extends Throwable> void myFunc(Class<T> exceptionType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, T { final String message = "some message"; throw exceptionType.getConstructor(String.class).newInstance(message); } 

or reconstruct found exceptions wrapped in a RuntimeException .

+7
source

You can use the newInstance method for the Class object.

0
source

Source: https://habr.com/ru/post/1234565/


All Articles