Почему происходит ошибка "missing return statement" в конструкции try-catch?
Ошибка missing return statement возникает, когда метод, который имеет тип возвращаемого значения (является не void ), ничего не возвращает оператором return .
Давайте посмотрим на ваш метод с точки зрения jdk.
Так, нужно постараться выполнить код в блоке try . Есть два варианта: код в блоке try выполнится или не выполнится (произойдёт исключение).
Если код в блоке try выполнится (исключения не произойдёт): из метода будет возвращена строка, считанная BufferedReader ‘ом. Всё ок.
Если код в блоке try не выполнится (произойдёт исклоючение): программа "перепрыгивает" в блок catch . В блоке catch ничего не возвращается. Программа будет выполнять метод дальше, но в методе больше ничего нет. И оператора return , который должен вернуть значение, тоже нет. А метод должен возвращать строку. Всё плохо, так быть не должно. Вот и причина ошибки.
Решение проблемы:
Нужно добавить оператор return в блок catch . Можно вернуть сообщение об ошибке, например:
Solved- Java missing return statement error
There is a good chance that you will face missing return statement error if you are new to Programming. This is a Java compile time error and it appears if you are missing any return stament from a method.
In this post, I will show you how to fix this error and a couple of examples with this error.
Example 1:
Let’s take a look at the below program:
If you write this program, your IDE will show you the missing return statement error. On IntelliJ-Idea, it looks as like below:
- getValue method is defined to return an int value, but we are not returning anything.
- either make getValue to return void:
- or, return an integer.
If we are defining a method that it is returning something, we have to return a value of the same type.
Example 2:
Now, let’s take a look at the below program:
I have changed the getValue method to take an integer as the parameter and the return value to String.
This method checks if the value of v, i.e. the passed parameter is equal to 0 or not. If yes, it returns the string Zero.
But, it still throws the same error.
This is because, we have a return statement for the if condition. But we don’t have any return statement if the if condition fails. So, we have to add one default return statement.
But, if you have a else statement at the end, you don’t have to add a return statement.
else block will run always if it fail for if and else if.
Conclusion:
No matter what, always check for all possible scenarios. If your method is working for some specific values, it might not work for some other values. Make sure to add the return statement for all possible scenarios.
Missing return statement in java
In Java, missing return statement is a common error which occurs if either we forget to add return statement or use in the wrong scenario.
In this article, we will see the different scenarios when missing return statement can occur.
Table of Contents
Missing return statement
Here are the few scenarios where we can get Missing return statement error.
Scenario 1
Let’s take an example, where we have a method that returns absolute value of the given positive number. In this example, we computed the absolute value but forgot to return it. When we compile this code, the compiler reports an error. See the example and output.
Solution
We can solve it by using two ways, either add return statement in the code or set return type as void in the method signature. See the examples below, wherein the first example we have added the return statement. We have also added another method getAbsolute2() and returned void from it in case we don’t want to return anything from the method.
Scenario 2
This error can also occur if we have used a return statement in if block. This return statement will execute only when if block executes. Since return statement depends on the if block condition, compiler reports an error. We have to either put return statement in else block or to the end of the method to resolve this.
Note: A method that has return type in its signature must have return statement.
Solution
If return statement is inside any block like if , for etc. then we need to add an extra return either in else block or in the last line of method body to avoid missing return type error. See the example and output.
That’s all about Missing return statement in java.
Was this post helpful?
Share this
Cannot find symbol Java
[Fixed] bad operand types for binary operator in java
Related Posts
Author
Related Posts
[Fixed] Unsupported class file major version 61 in Java
Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]
[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]
[Fixed] Unable to obtain LocalDateTime from TemporalAccessor
Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]
[Solved] Variable might not have been initialized in Java
Learn about how to solve Variable might not have been initialized in Java.
[Solved] Class names are only accepted if annotation processing is explicitly requested
Learn about how to fix class names are only accepted if annotation processing is explicitly requested in java.