3

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
SteamboatTMR
  • 65
  • 1
  • 7

2 Answers2

5

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.

Slaw
  • 37,820
  • 8
  • 53
  • 80
  • Thank you, so that means you can only have classes at the end of the import statement. Importing * would result in importing all classes under it, not including the package that is under it. – SteamboatTMR Oct 14 '19 at 08:35
1

To add on what @Slaw, There is no implicit subpackage import in java.

package a;
class A{}

and

package a.b;
   class B{}

If you want use B in A you have to import it explicitly as : import a.b.B; or import a.b.*;

Hope that could help

kourouma_coder
  • 1,078
  • 2
  • 13
  • 24