'finally块没有正常完成'Eclipse警告

Jos*_* D. 70 java try-catch-finally

Eclipse在以下代码中给出了警告:

public int getTicket(int lotteryId, String player) {
    try {
        c = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); 
        int ticketNumber;

        PreparedStatement p = c.prepareStatement(
                "SELECT max(num_ticket) " +
                "FROM loteria_tickets " +
                "WHERE id_loteria = ?"
                );
        p.setInt(1, lotteryId);
        ResultSet rs = p.executeQuery();
        if (rs.next()) {
            ticketNumber = rs.getInt(1);
        } else {
            ticketNumber = -1;
        }

        ticketNumber++;

        p = c.prepareStatement(
                "INSERT INTO loteria_tickets " +
                "VALUES (?,?,?,?)");
        p.setInt(1, lotteryId);
        p.setInt(2, ticketNumber);
        p.setString(3, player);
        p.setDate(4, new java.sql.Date((new java.util.Date()).getTime()));
        p.executeUpdate();

        return ticketNumber;
    } catch (Exception e) {
        e.printStackTrace();
    } finally { 
        if (c != null) {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

Man*_*yas 123

从中删除return语句.最终块被认为是清理块,通常不会返回它.

  • 我明白了,我应该在捕获结束时获得回报......谢谢 (3认同)
  • 但有什么害处吗?如果我有意识地这样做,了解这些影响? (2认同)

ALZ*_*ALZ 25

returnfinally"覆盖"进一步异常抛出.

public class App {
    public static void main(String[] args) {
        System.err.println(f());
    }
    public static int f() {
        try {
            throw new RuntimeException();
        } finally {
            return 1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

1


gei*_*ich 9

通常一个finally块永远不应该有一个return语句,因为它会覆盖其他return语句或Exceptions.

有关进一步阅读和更详细的背景,请参阅问题

catch中的return语句的行为,最后


Adi*_*dil 5

通过在块中同时使用returnand throw语句,finally您将收到警告,例如,您将在以下finally块中收到相同的警告:

...
}finally{
        throw new RuntimeException("from finally!");
}
...
Run Code Online (Sandbox Code Playgroud)