Monday, November 18, 2024
Google search engine
HomeLanguagesJavaMethod Class | getGenericExceptionTypes() Method in Java

Method Class | getGenericExceptionTypes() Method in Java

The getGenericExceptionTypes() method of java.lang.reflectMethod class returns an array of Type objects representing Exceptions thrown by the method object to handle exception. All the exceptions handled by method using thrown clause are returned as array of Type objects using this method. This method returns an array of length 0, if the method, on which this method is applied, declares no exceptions in its throws clause. Example:

Code:
public class demo{
    public void setValue(String value)
    throws ClassNotFoundException, ArrayIndexOutOfBoundsException, 
            ArithmeticException {}
}
Explanation:
In the above method when we going to apply getGenericExceptionTypes() method
it is going to return array of the exception types.
Array = {
          java.lang.ClassNotFoundException,
          java.lang.ArrayIndexOutOfBoundsException,
          java.lang.ArithmeticException,
        }

Syntax:

public Type[] getGenericExceptionTypes()

Return Value: It returns an array of the exception types thrown by the this Method object Exception: This method throws following exceptions:

  • GenericSignatureFormatError – if the generic method signature is not same as the format specified in The JVM Specification.
  • TypeNotPresentException – if Exception Types specified by throws clause refers to a non-existent type declaration.
  • MalformedParameterizedTypeException – if the underlying executable’s throws clause refers to a parameterized type that cannot be instantiated for any reason.

Below programs illustrates getGenericExceptionTypes() method of Method class: Program 1: Print all Exception Types thrown by a Method with the help of getGenericExceptionTypes() 

Java




/*
* Program Demonstrate how to apply
* getGenericExceptionTypes() method
*/
import java.lang.reflect.Method;
import java.lang.reflect.Type;
 
public class GFG {
 
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = demoClass.class;
 
            // create parameter type of string
            Class[] parameterTypes = { String.class };
 
            // get list of method objects
            Method[] methods = classobj.getMethods();
 
            // loop through all methods
            for (Method m : methods) {
 
                if (m.getName().equals("setValue")
                    || m.getName().equals("getValue")) {
 
                    // apply getGenericExceptionTypes() method
                    Type[] genericExceptions = m.getGenericExceptionTypes();
 
                    // print exception Types thrown by method Object
                    System.out.println("Generic Exception Thrown by Method: "
                                       + m.getName());
 
                    System.out.println("Generic Exception Type Array length: "
                                       + genericExceptions.length);
 
                    // If method has Exception then print
                    if (genericExceptions.length > 0) {
 
                        System.out.println("Exception class object details:");
 
                        for (Type type : genericExceptions) {
 
                            System.out.println(type.getTypeName());
                        }
                    }
                    System.out.println();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// a simple class
class demoClass {
 
    String value;
 
    // throw some exception by method
    public void setValue(String value)
        throws ClassNotFoundException,
               ArrayIndexOutOfBoundsException,
               ArithmeticException
    {
        this.value = value;
    }
 
    // method throwing no exception
    public String getValue()
    {
        return this.value;
    }
}


Output:

Generic Exception Thrown by Method: getValue
Generic Exception Type Array length: 0

Generic Exception Thrown by Method: setValue
Generic Exception Type Array length: 3
Exception class object details:
java.lang.ClassNotFoundException
java.lang.ArrayIndexOutOfBoundsException
java.lang.ArithmeticException

Program 2: Check for a specific Exception 

Java




/*
* Program Demonstrate how to
* apply getGenericExceptionTypes() method
*/
 
import java.lang.reflect.Method;
import java.lang.reflect.Type;
 
public class GFG {
 
    // a simple class
    class GFGSampleClass {
 
        String value;
 
        // throw some exception by method
        public void setValue(String value)
            throws ClassNotFoundException,
                   ArrayIndexOutOfBoundsException,
                   ArithmeticException
        {
            this.value = value;
        }
    }
 
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = GFGSampleClass.class;
 
            // get list of method objects
            Method[] methods = classobj.getMethods();
 
            // get Method Object for setValue
            Method method = null;
            for (Method m : methods) {
                if (m.getName().equals("setValue"))
                    method = m;
            }
 
            // check whether method throw
            // ArithmeticException Exception
            Type arithmeticExClassobj = ArithmeticException.class;
 
            boolean response = isCertainExceptionIsThrown(method,
                                                          arithmeticExClassobj);
            System.out.println("ArithmeticException"
                               + " is thrown by setValue(): " + response);
 
            // check whether method throw
            // IndexOutOfBoundsException Exception
            Type exceptionObj = IndexOutOfBoundsException.class;
 
            response = isCertainExceptionIsThrown(method,
                                                  exceptionObj);
            System.out.println("IndexOutOfBoundsException"
                               + " is thrown by setValue(): " + response);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /*
    * Return true if the given method throws the
    * exception passed AS Parameter.
    */
    private static boolean
    isCertainExceptionIsThrown(Method method, Type exceptionName)
    {
        // get all exception list using getGenericExceptionTypes()
        Type exceptions[] = method.getGenericExceptionTypes();
 
        for (int i = 0; i < exceptions.length; i++) {
            // check exception thrown or not
            if (exceptions[i] == exceptionName) {
                return true;
            }
        }
 
        return false;
    }
}


Output:

ArithmeticException is thrown by setValue(): true
IndexOutOfBoundsException is thrown by setValue(): false

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericExceptionTypes–

RELATED ARTICLES

Most Popular

Recent Comments