Search code examples
javajdbcexceptionsqlexceptionthrows

How can I call my custom exception when an SQLException occurs?


Suppose I have the following lines of code,

       Class.forName(JDBC_DRIVER);
       dbConnection = DriverManager.getConnection(DB_URL, USER, PASS);

Now what I want is that when an SQLException is caught, I want to throw my custom exception from the catch field of the SQLException, I mean is it possible to do so or is there an alternative way to do so?

AND my custom exception is ErrorToDisplayException as:

    public class ErrorToDisplayException extends Exception{

public ErrorToDisplayException(Throwable e) {
}
    }

my code is as:

   try {        
    //Register JDBC driver
       Class.forName(JDBC_DRIVER);
       dbConnection = DriverManager.getConnection(DB_URL, USER, PASS);
   }catch(final SQLException se){
    // Handle errors for JDBC
       throw new ErrorToDisplayException(se);
   }

Now what happens is that when the compiler reaches at }catch(final SQLException se){ it does not go to its catch body and just breaks away, don't know why?


Solution

  • You mean somthing like that or I don't get it?!

    try {
        Class.forName(JDBC_DRIVER);
        dbConnection = DriverManager.getConnection(DB_URL, USER, PASS);
    } catch (SQLException e) {
        throw new MyException(e);
    }
    

    or you mean to replace some standard exception by own type in all places?