不要在finally块中返回值

不要在finally块中返回值


 1/**
 2 * Author: wangy325
 3 * Date: 2024-07-17 12:37:27
 4 * Description: 不要在finally块里写返回语句, finally块里的值总是最终的返回值
 5 **/
 6
 7class TryF {
 8    public static void main(String[] args) {
 9        System.out.println(how_finally_works(2, 3));
10        System.out.println("---------");
11        System.out.println(how_finally_works(2, 0));
12        System.out.println("---------");
13        System.out.println(how_finally_works("a", "b"));
14        System.out.println("---------");
15
16    }
17
18    /**
19     * 和python的表现一模一样
20     * 
21     * @param x
22     * @param y
23     * @return
24     * @see try_excep.py
25     */
26    @SuppressWarnings("finally")
27    static float how_finally_works(Object x, Object y) {
28        try {
29            return (int) x / (int) y;
30        } catch (ArithmeticException e) {
31            e.printStackTrace();
32            System.out.println("can not devide by 0");
33            return 0;
34        } finally {
35            System.out.println("finally...");
36            return -1;
37        }
38    }
39}