I'm trying to put try/catch block around my connection in Java. Here is example of my code:
public static Connection getConnection() throws Exception, SQLException {
try{
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://IP\\:Port;databaseName=DB";
String username = "username";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
}catch (SQLException e){
System.out.println(e.getMessage());
}
return conn;
}
My code gives me error on line where is my * return conn; *! saying that: conn cannot be resolved to a variable.
Also I want to put try catch block around my PasswordAuthentication but everything that I tried did not work for me. Here is my code for that part:
class EmailSender{
private Session session;
//Checking for authentication, taking host and port information
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "IP");
props.put("mail.smtp.port", "PORT");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
//returning user name and password to connect to email server
return new PasswordAuthentication("Username", "password");
}
});
}
I tried to put try/catch block around entire code in this part, also around just session part but nothing did not work for me. Can anyone help me with this problem?