javainvocationtargetexception

why must I import InvocationTargetException since it's in java.lang?


I'm trying to catch InvocationTargetException in my file, but I get this error if I do not explicitly write the import statement for it.

Since it's under a sub package of java.lang, I don't know why I have to import it.

//this is the import statement that worked

import java.lang.reflect.InvocationTargetException;

This is the error message:

source\DatabaseDemo.java:38: error: cannot find symbol
        }catch (NoSuchMethodException | InstantiationException | SQLException | ClassNotFoundException | IllegalAccessException | InvocationTargetException e ){
                                                                                                                                  ^
  symbol:   class InvocationTargetException
  location: class DatabaseDemo

Solution

  • There is no concept of sub-packages in Java. We humans view packages as hierarchical for convenience's sake and because source code is typically structured into a hierarchy of directories. However, at a language level no such hierarchy exists. In other words, java.lang.reflect is not a "sub-package" of java.lang. And since only the classes of the java.lang package are auto-imported you have to explicitly import InvocationTargetException.