0

Is it good practice to handle exception like this? Or there is any better alternative way to do it? The code works fine but I feel that not all the Exceptions of getAllGrades() method will be shown because of throws added infront of connection(). Please correct me if I'm wrong.

package DAO;

import java.sql.*;
import java.util.ArrayList;

public class StudentDAO {
    static Connection con;
    static PreparedStatement stmt;
    static ResultSet rs;
    public static void connection() throws Exception {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "xxx", "yyy");
    }
    public static ArrayList<String> getAllGrades() {
        try {
            connection();
            stmt=con.prepareStatement("SELECT DISTINCT grade from student");
            rs=stmt.executeQuery();
            ArrayList<String> grades=new ArrayList<String>();
            while(rs.next()) {
                grades.add(rs.getString(1));
            }
            con.close();
            return grades;
        }
        catch(SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;        
    }
}
Maaz
  • 25
  • 5
  • `connection()` is within the try, so it will be caught and printed. But, if an Exception is thrown, you are not closing your connection. – Scary Wombat Sep 06 '22 at 05:07
  • @ScaryWombat It can be fixed by adding "finally" and writing connection close there, if I'm not wrong? – Maaz Sep 06 '22 at 05:16
  • 1
    Yep, but I think that `Connection` implements autoCloseable, so just use a try-with-resources. – Scary Wombat Sep 06 '22 at 06:29

0 Answers0