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";
A static block can throw only a RunTimeException, or there should be a try and catch block to catch a checked exception. A static block occurs when a class is loaded by a class loader.
A static method can also provide an array as a return value.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Restrictions on static blocks and static methodsYou cannot access a non-static member (method or, variable) from a static context. This and super cannot be used in static context. The static method can access only static type data (static type instance variable). You cannot override a static method.
The problem is caused by the fact, that UnknownInputException
is probably a nested class, and if you instantiate it with the new
operator, 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 UnknownInputException
as static
like this:
private static class UnknownInputException extends Exception { ... }
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, return
ing value after the throw
line is unnecessary, as execution will never reach that line.
The variable this is not noted in the given example code, so it can not cause an error.
The code return "unknownInput";
is redundant since never executed.
There must be another static method in which this
is used, that causes the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With