Can static methods that return a value throw an exception?

I have a static method that returns a String, but in the event that the string that is passed does not match one of several words, I want to throw an exception. The code below is just an example of what I'm trying to do, but I continue to receive the message β€œnot a static variable that cannot be referenced from a static context” in the line where I threw an exception. Basically, the return value from getMsg should be valid or the program cannot act, 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"; 
+7
source share
5 answers

The problem is caused by the fact that UnknownInputException is probably a nested class, and if you create an instance with the new operator as a nested class, it must have access to the "parent" object - which does not exist because the class was created in a static context. For more information about this, see Static Method Returning an Inner Class .

A possible solution would be to declare UnknownInputException as static as follows:

 private static class UnknownInputException extends Exception { ... } 

Of course, you will not be able to access any instances of (non-static) methods and / or fields of this class, but this may not be a problem in your case (especially in the case of the Exception class).

In addition, the return ing value after the throw line is not required, since execution will never reach that line.

+5
source

This variable is not specified in this code example, so it cannot cause an error.

return "unknownInput"; code return "unknownInput"; is redundant as it has never been executed.

There must be another static method that uses this , which causes an error.

+2
source

An unknown event is an inner class. As soon as I made it static, the code compiled. Thanks for helping the guys.

+2
source

Its completely legal in java to throw exceptions from static methods. However, the code you presented here cannot even be compiled :) Therefore, provide all the code.

The error you get here just says that you are using non-static data fields defined by a class from a static method. The static method does not belong to any instance, but the data field does ...

0
source

First, the string return "unknownInput"; will never be executed. Is there a dead code warning there?

And your method does not have a 'this' link, are you sure that it complains about this method?

0
source

All Articles