Administrator
发布于 2023-05-24 / 55 阅读
0
0

Java Fundemental Feature II

Finally & Return

  1. 在try-chtch-finally块中,无论前面的部分是否有return语句,finally块都会被执行。
public class TestFinally {

    public static void main(String[] args) {
        System.out.print(decision());
    }

    public static boolean decision(){
        try{
            return true;
        } finally {
            System.out.println("run finally");
        }
    }

}

输出:

run finally
true
  1. 而且,当finally块中有return语句时,它会覆盖try块和catch块中的return语句,这也是编译器提示警告的原因。
public static void main(String[] args) {
        System.out.print(decision());
    }
    public static boolean decision(){
        try{
            return true;
        } finally {
            return false;
        }
    }


输出:

false
  1. 在finally中包含return时,无法将异常再抛出,也就是说客户端得到的不是异常而是finally中return的返回值。
  public static void main(String[] args) {
        try {
            System.out.print(decision());
        } catch (IOException e) {
            System.out.print(e.getMessage());
        }
    }


    public static boolean decision() throws IOException {
        try{
            throw new Exception("try exception");
        } catch (Exception e){
            throw new IOException("catch exception");
        } finally {
            return false;
        }
    }

输出

false

Pair

org.apache.commons.lang3.tuple.Pair

image-20240129163300639

创建pair

 Pair<String, Integer> pair = Pair.of(rowKey, sum);

获取key value

getKey()
getValue()

image-20240129163404088


评论