Return method with throw

2

This method has the return type Connection , but in blocks catch there is no return conn and there is no compilation or execution error. I think it's for throws and throw but I do not know exactly why.

    public static Connection getConexao() throws SQLException, ClassNotFoundException {

    Connection conn = null;
    try {
        Class.forName(DRIVER_CONEXAO);
        conn = DriverManager.getConnection(STR_CONEXAO + DATABASE, USUARIO, SENHA);

        return conn;

    } catch (ClassNotFoundException e) {
        throw new ClassNotFoundException(
                "Driver MySql não foi encontrado " + e.getMessage());

    } catch (SQLException e) {
        throw new SQLException("Erro ao conectar "
                + "com a base de dados" + e.getMessage());
    }
}
    
asked by anonymous 13.11.2015 / 14:55

1 answer

1

It is by the assumption that you are in the question, and also because you are throwing another exception (which is unusual and probably something wrong to do). If an exception is thrown, return is not required. If you take this exception, it does not compile.

See the example running . And see or compile .

Anyway if this is not just an example, it is the wrong way to use exception. Read about it in the tag . There are lots of questions on the subject where, me and other users here talk about the right way to use exceptions, and how most programmers use it wrongly.

    
13.11.2015 / 15:05