1

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?

1
  • You need to declare the Connection object outside the try catch block, its scope is limited. Commented Aug 11, 2015 at 19:38

2 Answers 2

4

Since conn is defined inside the try { ... }, it is not known outside of that block (variables have a "scope" where they are known). You have two choices:

a) Declare your conn before the try and just assign it inside...

Connection conn = null;
try {
   conn = ...;

b) Move your return inside the try block and return null at the end. This way, it will return conn if everything went ok and null, if the exception was caught.

For the 2nd part, I don't see why there should be any problem wrapping a try catch around the Session.getInstance():

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");

    try {

      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");
                }
              });
     } catch(RuntimeException e) {
         e.printStackTrace(); // for example
     }
}

Of course this only prevents the method from throwing an exception further out. It will lead to session being null.

Sign up to request clarification or add additional context in comments.

5 Comments

beat me to it by 2 seconds
I would suggest putting it in another question. And honestly, I have no idea what your problem is, since the question is worded quite unclear. what excactly doesn't work? The only thing that could probably throw an exception is the Session.getInstance and you should be able to wrap a try-catch around that. I'll update my answer.
Problem was inside of the catch block I had SQLException instead of RuntimeException.
Why should a javax.mail code throw an SQLException? Is this the same code you used then? Anyway, you can of course also catch the SQLException instead of RuntimeException (which I just chose because afaik it was the only possible one there).
I just made mistake putting SQLException instead of runtime.
1

Adding one important point to the Florian Schaetz answer.

Should have two catch block for case one

For

Class.forName("com.mysql.jdbc.Driver"); 

we should catch ClassNotFoundException

and for

Connection conn = DriverManager.getConnection(url, username, password);

we should catch SQLException

so your final code should be with two catch blocks

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 (ClassNotFoundException e){
            System.out.println(e.getMessage());
        }
        catch (SQLException e){
            System.out.println(e.getMessage());
        }
        return conn;
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.