I recently learned about Java's Try-with-Resources for autoclosable resources. I was rewriting a JSP to use the Try-with-Resources instead of a Try-Catch. When I took out the database driver's instantiation, the code still worked. How is that possible?
I am using Apache Tomcat, and think it must be something special Tomcat is doing, because in a regular Java class the driver.newInstance() must be in a try-catch block. In Tomcat, I removed it completely, and everything still worked like normal.
I went from this:
try{
// Set up the connection
Class.forName(driverName).newInstance();
connection = DriverManager.getConnection(connectionURL, name, password);
...more stuff
}
to this:
try(Connection con = DriverManager.getConnection(connectionURL, name, password)){
...more stuff
}
Why does this work?