Imagine you have a method like:
public void doGreatThings() throws CantDoGreatThingsException, RuntimeException {...}
Is there any way to programmatically get the declared thrown exceptions by way of reflection?
// It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class]
You can use getExceptionTypes()
method. You will not get Exception[]
since such array would expect exception instances, but you will get instead Class<?>[]
which will hold all thrown exception .class
.
Demo:
class Demo{
private void test() throws IOException, FileAlreadyExistsException{}
public static void main(java.lang.String[] args) throws Exception {
Method declaredMethod = Demo.class.getDeclaredMethod("test");
Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes();
for (Class<?> exception: exceptionTypes){
System.out.println(exception);
}
}
}
Output:
class java.io.IOException
class java.nio.file.FileAlreadyExistsException
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