I have a singleton connector object that helps in connecting to a mysql database.
public class Connector{
private Connector(){
}
public static Connector getInstance(){
if(unique == null) unique = new Connector();
return unique;
}
public void connect() throws SQLException{
conn = (Connection) DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
if(conn != null) System.out.println("Connected");
}
public void close() throws SQLException{
if(conn != null) conn.close();
}
}
But naturally I'm bubbling up the exceptions for the caller to handle. This is my calling client.
Connector connector = Connector.getInstance();
try {
connector.connect();
} catch (SQLException e) {
System.out.println("Connected now");
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
connector.close();
System.out.println("Connection closed");
}
Now the connector doesn't compile as it wants me to wrap the finally within a try catch since the method close()
also throws an exception. This would mean I'd have to write the code like.
finally {
try {
connector.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Connection closed");
}
This somehow doesn't look right. What's the right way to deal with this situation. Thanks in anticipation.
Use the decorator pattern to handle this. You can change your Connector
class to implement AutoCloseable
(which just has one method: public void close()
) and ensure that there is no exception thrown. Then you can use a try-with-resources when working with Connector
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments