Вопрос

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?

Это было полезно?

Решение

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?

Другие советы

First:

class MyCustomException extends Exception {
    public MyCustomException(Throwable e) {
    }
}

Then:

try {
    Class.forName(JDBC_DRIVER);
    dbConnection = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
    throw new MyCustomException(e);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top