Finally, as part of exception handling, it can only be used in try/catch statements, and comes with a statement block, indicating that this statement will eventually be executed (regardless of whether an exception is thrown or not), and is often used when resources need to be released.
Before, when writing crawlers, the database connection frequency was very high. Sometimes the data was not processed well. After the SQL error was reported, an exception was thrown but the subsequent database connection was not disconnected. This resulted in the end that the number of database connections was too large and no longer allowed to connect (because it was a personal library, I directly restarted). This operation of releasing the database connection can be performed in finally.
First, let’s take a look at the code that is not finally (it can’t be run directly, just understand what it means)
Connection conn;Statement stmt;try{ conn = DriverManager.getConnection(url,userName,password); stmt = conn.createStatement; String sql = "sql";//sql stmt.executeUpdate(sql); stmt.close(); conn.close();}catch(Exception e){ e.printStackTrace();}When the program is running normally, no exception is thrown, no problem.
However, when the program throws an exception (sql error occurs), the statement in try is not executed and the statement in catch is directly executed, which causes a database connection not to be closed normally. If the amount of data becomes larger, the maximum number of connections in the database reaches the upper limit, and new connections are no longer allowed.
Then the usefulness of finally can be reflected now
Connection conn = null;Statement stmt = null;try { conn = DriverManager.getConnection(url,userName,password); stmt = conn.createStatement; String sql = "sql";//sql stmt.executeUpdate(sql); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } finally{ if(stmt! = NULL){ stmt.close(); } if(conn! = NULL){ conn.close(); } } In this way, even if SQL runs an error and throws an exception, and then make another judgment on the database connection in the final code, it can ensure that the database connection resources will not be wasted for no reason.
The above is the usage of finally in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!