Switch statement found in Java method Does the method need to return something?
I was reading some Java textbooks trying to learn a new language, and I encountered this method
private String monthName (int month) { // bad example since this method needs to return a String switch (month) { case 1: return "January"; case 2: return "February"; ... case 12: return "December"; } }
The statement after this code says:
So in Java, I assume that if a method has the word "string" before the method name, does it have to return a string? The problem with this switch statement is that it may not meet the conditions of the case statement, and the execution just falls out from the bottom? Is it necessary to always return values for methods that are not marked void?
Solution
A method signature is a contract that specifies what it takes as a parameter and what it is obliged to return A method that declares that it returns something other than void must return something or throw something. It is not allowed to turn around without returning anything (if any, the variable that allocates the return value from the method call must still be allocated)
Specifically, if a method is declared to return a string, each possible path obtained through the method must end with returning a string, return null (null is the allowable value of any reference type), or throw a throwable instance This is what the quoted paragraph tells you. The compiler can detect that you don't do it and complain about it
If the integer passed in is not within the expected range, you can throw an exception here It's a good thing for your methods to verify that they are receiving reasonable values for their parameters Using the default value or returning null is not good because it will not immediately expose the problem, but will provide the caller with a value that may be meaningless, and it may be more difficult to debug what happened because the error is visible There is still a long way to go from the cause of the problem This method can be written as:
private String monthName (int month) { // bad example since this method needs to return a String switch (month) { case 1: return "January"; case 2: return "February"; ... case 12: return "December"; default: throw new IllegalArgumentException("found unexpected value " + month); } }
In this way, the compiler will not complain, and any value out of range will attract your attention
awake to:
>Many people insist that all switches should include defaults so that unhandled conditions are not passed silently. > java. Util date / calendar API number is the month starting from 0 instead of 1 in the example; If you use the calendar to find the month and pass the int to this method, it is easy to return the wrong month Handling errors as close to the source as possible makes tracking problems easier