Eclipse give me that warning in the following code:
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; } }
What is wrong with my code?
You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System. exit(0) method, at the end of the catch block which is just before the finally block.
A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.
It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block. System.
A finally block always executes, regardless of whether an exception is thrown.
remove return statement from it. Final block is considered to be cleanup block, return is not generally expected in it.
The return
from finally
"overrides" further exception throwing.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With