Java – use try catch finally to return the type
•
Java
See English answers > java's return value in try catch finally mechanism4
private Integer getnumber() {
Integer i = null;
try {
i = new Integer(5);
return i;
} catch(Exception e) {
return 0;
} finally {
i = new Integer(7);
}
}
This method returns 5 instead of 7
Thank you in advance
Solution
This happens because try The finally block of catch is finally in try Run after the code in catch is completed (whether successful or not); In the case of your code, this is the time when the return I occurs
Because of this behavior, the value of I is placed in the return variable of the method before you assign it a new value 7 The following will be valid:
private Integer getnumber(){
Integer i = null;
try {
i = new Integer(5);
}
catch(Exception e){
i = new Integer(0);
}
finally{
i = new Integer(7);
}
return i;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
