在 try catch 塊中返回語句

雖然這是不好的做法,但可以在異常處理塊中新增多個 return 語句:

 public static int returnTest(int number){
    try{
        if(number%2 == 0) throw new Exception("Exception thrown");
        else return x;
    }
    catch(Exception e){
        return 3;
    }
    finally{
        return 7;
    }
}

此方法將始終返回 7,因為在返回任何內容之前執行與 try / catch 塊關聯的 finally 塊。現在,最終有了 return 7;,這個值取代了 try / catch 返回值。

如果 catch 塊返回原始值並且隨後在 finally 塊中更改了原始值,則將返回 catch 塊中返回的值,並且將忽略 finally 塊中的更改。

以下示例將列印 0,而不是 1

public class FinallyExample {

    public static void main(String[] args) {
        int n = returnTest(4);
        
        System.out.println(n);
    }

    public static int returnTest(int number) {
        
        int returnNumber = 0; 
        
        try {
            if (number % 2 == 0)
                throw new Exception("Exception thrown");
            else
                return returnNumber;
        } catch (Exception e) {
            return returnNumber;
        } finally {
            returnNumber = 1;
        }
    }
}