Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out what exceptions a method throws programmatically

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]
like image 794
kodai Avatar asked Jan 05 '23 18:01

kodai


1 Answers

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
like image 57
Pshemo Avatar answered Jan 08 '23 09:01

Pshemo