Finally on the impact of the return value

1, on the impact finally return value


We know that after finally returned to perform before the return statement is executed in the try.

If you try the last return a variable, and that in the end what will finally be returned to this variable after modification?

See example directly on the test code:

class YfModel{
    private String name;

    public YfModel(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class ExceptionYf {
    public static int getIntValue1(){
        int result =9;
        try{
            result++;
            return result;
        }finally {
            //修改result的值
            result++;
        }
    }

    public static int getIntValue2(){
        int result =9;
        try{
            result++;
            return result;
        }finally {
            //finally里直接return
            return ++result;
        }
    }

    public static String getStringValue(){
        YfModel yfModel = new YfModel("default");
        try{
            yfModel.setName("yy");
            return yfModel.getName();
        }finally {
            //finally里修改对象的属性值
            yfModel.setName("ff");
        }

    }

    public static YfModel getModelValue(){
        YfModel yfModel = new YfModel("default");
        try{
            yfModel.setName("yy");
            return yfModel;
        }finally {
            yfModel.setName("ff");
        }
    }

    public static void main(String[] args){
        System.out.println("valueInt1="+ getIntValue1());
        System.out.println("valueInt2="+ getIntValue2());
        System.out.println("valueStr="+ getStringValue());
        System.out.println("valueModel="+ getModelValue().getName());
    }
}
View Code

The code returns the result:

valueInt1=10
valueInt2=11
valueStr=yy
valueModel=ff

 

in conclusion:

a, the basic type or constant (e.g., String) finally even in modified, it will not affect the return results.

b, if the object type, finally there is the impact of modifying objects returned results. (Because the pointer is a pointer memory area is the same as the transmitted complex objects.)

So do not return in the finally inside. This is not standard practice.

 

2, finally there not to throw an exception


and then finally in abnormal need finally log in to capture the play, not to be thrown out, otherwise it will cover the Central Plains and some try catch exception information.

 

3, finally will execute it


Typically finally block will be executed, commonly used in the closing operation of the stream.

But if try catch in the implementation of the action represents a virtual machine System.exit terminated, it will not be executed finally.

 

Guess you like

Origin www.cnblogs.com/yangfei629/p/11444086.html