Example1Exception and Example1Method belong together in the same file. It would not make sense to put them in separate files.
public class Example1
{
public class Example1Exception extends Exception
{
public Example1Exception(String message)
{
super(message);
}
}
public static void Example1Method() throws Example1Exception
{
throw new Example1Exception("hello"); //error: non-static variable this cannot be referenced from a static context
}
}
How can I throw Example1Exception in Example1Method?
(Assuming you actually declare Example1Exception
using a class declaration..., and that the method declaration is fixed too...)
Example1Exception
is an inner class - it needs a reference to an enclosing instance of the outer class.
Options:
static
Personally I'd usually go for the last option - why do you want it to be a nested class anyway? Why would it not make sense to put them in separate files? What do you gain by having it as a nested class, other than a bunch of complexity? Do you really want people to declare catch (Example1.Example1Exception ex) { ... }
If you really want it to be nested, you probably just want it to be a non-inner class - you're not using the implicitly-required reference to an instance of Example1
.
See more on this question at Stackoverflow