Unable to import nested custom exception class
I have this class:
public class SomeClass {
public void someMethod() {} throws someException
public class someException extends Exception { // Exception class
public someException(String message) {
super(message);
}
}
}
Another class:
public class SomeOtherClass {
public static void main (String[] args) {
SomeClass obj = new SomeClass();
try {
obj.someMethod();
} catch (someException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Eclipse complains that "someException could not be resolved for the type." I tried to add
import SomeClass.someException
But then he says "Import of SomeClass could not be allowed"
You could of course put someException in a separate file and not nest it, is that the only way?
+3
source to share
1 answer
You should be able to use the class by giving it a class name SomeClass.someException
. If you want to import it, you have to put your code in a package. Then you can:
import yourpkg.SomeClass.someException;
Also, here you have a little syntax:
public void someMethod() {} throws someException
he should be
public void someMethod() throws someException {}
(But it might have been a typo in your question.)
You might also consider creating a nested class static
if you don't really need to reference the surrounding object:
public static class someException extends Exception {
...
}
+3
source to share