1

I keep getting an error stating I need a catch clause to accompany the try (inside public Connection getConnection()). I dont understand why the compiler isn't noticing the catch directly under the try. Does anyone know why it won't compile? I checked all my brackets as well...

package crud.data;

import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ConnectionPool
{
       private static ConnectionPool pool = null;
       private static DataSource dataSource = null;


       private ConnectionPool()
       {
           try
           {
                InitialContext ic = new InitialContext();
                dataSource = (DataSource)           
                        ic.lookup("java:/comp/env/jdbc/acm14n");
           }
           catch (NamingException e)
           {
                System.out.println(e);
           }
     }

     public static synchronized ConnectionPool getInstance()
     {
            if(pool == null)
            {
                 pool = new ConnectionPool();
            } 
            return pool;
     }

     public Connection getConnection()
     {
         try
         {
             return dataSource.getConnection();
         }
         catch  (SQLException e)
         {
            System.out.println(e);
            return null;
         }  
     }

     public void freeConnection(Connection c)
     {
         try
         {
            c.close();
         } 
         catch (SQLException e)
         {
                System.out.println(e);
         }
     }
}
chb
  • 1,727
  • 7
  • 25
  • 47
Alexis M
  • 21
  • 3
  • As an aside, I would allow the `getConnection()` to throw the `SQLException`. Otherwise, in whatever code you have, you will end up checking to see if the returned value is `null`. IMHO, this paradigm clutters the code. Catch the (essentially) unrecoverable exception rather than attempting to check for null everywhere. – KevinO Apr 10 '18 at 02:35
  • 1
    Get in the habit to indent your code so that the structure is clear. This is a pain to read. – Robert Apr 10 '18 at 03:24
  • Compiles for me. Are you sure you are posting the right code? – Robert Apr 10 '18 at 03:28
  • Exactly!! I dont see any errors so maybe its with my other files..... – Alexis M Apr 11 '18 at 17:30

0 Answers0