Eclipse的警告“终于阻止不正常完成”

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; } } 

我的代码有什么问题?

从中删除返回语句。 最终块被认为是清理块,通常不会在其中返回。

finallyreturn “重写”进一步的exception抛出。

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

1

通常情况下, finally块不应该有返回语句,因为它会覆盖其他return语句或Exceptions

为了进一步阅读和更详细的答案的背景,请参阅问题

返回语句在catch和finally中的行为

finally语句中使用returnthrow语句,你将得到警告,例如,你将得到与下面的finally块一样的警告:

 ... }finally{ throw new RuntimeException("from finally!"); } ...