I have a static method that returns a String, but in the event that the string that is passed in does not match one of several words, I want to throw an exception. The code below is just a sample of what I am trying to do, but I keep getting “non static variable this cannot be referenced from a static context” message on the line where I throw the exception. Basically, the return value from getMsg has to be valid, or the program cannot proceed, so I need a way to catch this.
public static String getMsg(String input) throws UnknownInputException{
if (input.equals("A")){
return "key for A";
}
throw new UnknownInputException("Some Message");
return "unknownInput";
The problem is caused by the fact, that
UnknownInputExceptionis probably a nested class, and if you instantiate it with thenewoperator, as a nested class, it should have access to a “parent” object – which doesn’t exist since the class was instantiated in a static context. For more information about this, see Static method returning inner class.A possible solution would be to declare
UnknownInputExceptionasstaticlike this:Of course, you won’t be able to access any instance (non-static) methods and/or fields from this class, but that might not be an issue in your case (especially in case of an Exception class).
Also,
returning value after thethrowline is unnecessary, as execution will never reach that line.