1

I am created a database class to understand singleton class better and well as learning java.However i am getting an unreported exception that i can't seem to fix.

Call

private Connection con = ConnectionManager.getConnection();

Netbeans tell me that i have an unreported exception here but here is the getConnection Method

public static Connection getConnection() throws SQLException  {
    boolean read = ReadFromConfig();
    if (read == true) {
         try {
            con = DriverManager.getConnection(urlstring, user, pass);
        } catch (SQLException ex) {
            throw new SQLException("Connection failed: " + ex);
        }
    } 
    return con;
}
Yogev Levy
  • 325
  • 3
  • 16
user2650277
  • 6,289
  • 17
  • 63
  • 132
  • 3
    The `try-catch` block in `getConnection()` is not only useless, it's harmful. It's destroying the original `SQLException` and losing information about the reason. You need to handle the exception in the code where you call `getConnection()`. – Kayaman Jan 25 '17 at 08:41
  • I think you are creating a new exception and maybe destroying "ex" when you do: "throw new SQLException("Connection failed: " + ex);" I would replace this line for: " **System.out.println("Connection failed: "); ex.printStackTrace();** ". Doing this you keep the first (and true) exception, and the console will print the error in case it is reached. – Amnor Jan 25 '17 at 08:50
  • The signature of _your_ `getConnection` tell the compiler that it could throw an SQLException so you need to encapsulate this code in a try catch block (just like you did with `DriverManager.getConnection` who throw SQLException too). But this is bad design to catch and throw an new one. – AxelH Jan 25 '17 at 08:54

1 Answers1

1

I suspect that the problem is caused by the static getConnection() function invocation. You are defining a method that can throw the SQLException (you define this in the method signature throws SQLException) and for this reason when you invoke it you necessary have to add the case where the possible thrown exception can be catch at the invocation time. The following fragment of code shows you how to solve the problem:

public class Test {
  public static int getConnection() throws Exception  
  {
    int result = 1;
    try 
    {
      result = 2;
    } 
    catch (Exception ex) 
    {
      throw new Exception("Connection failed: " + ex);
    }
    return result;
  }

  public static void main(String[] args) {
    try
    {
      Test.getConnection();
    }
    catch (Exception e)
    {
      // do something
    }
  }
}
acornagl
  • 521
  • 5
  • 24