How to throw exception in static method, both in same class

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?

Jon Skeet
people
quotationmark

(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:

  • Provide it with a reference (but why?)
  • Make it a nested (but non-inner) class by changing the declaration to include static
  • Make it a top-level class

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.

people

See more on this question at Stackoverflow