Interview question
How do you handle SQLException properly in JDBC applications? JDBC applications में SQLException को सही से कैसे handle करें?
Answer
SQLException is a checked exception carrying database-specific error information (SQL state, vendor error code, and a chain of related exceptions), and connections/statements/result sets must be properly closed even when errors occur.
public List<User> getUsers() {
List<User> users = new ArrayList<>();
String sql = 'SELECT id, name FROM users';
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
users.add(new User(rs.getInt('id'), rs.getString('name')));
}
} catch (SQLException e) {
// SQLException carries extra diagnostic info beyond getMessage()
System.out.println('SQL State: ' + e.getSQLState());
System.out.println('Error Code: ' + e.getErrorCode());
System.out.println('Message: ' + e.getMessage());
// SQLException can be CHAINED - multiple related exceptions
SQLException next = e.getNextException();
while (next != null) {
System.out.println('Chained: ' + next.getMessage());
next = next.getNextException();
}
throw new RuntimeException('Failed to fetch users', e); // wrap and rethrow with context
}
return users;
}
// try-with-resources handles closing automatically, even on exceptions -
// this avoids the old, verbose pattern of manually closing in finally blocks:
// finally {
// if (rs != null) try { rs.close(); } catch (SQLException e) {}
// if (pstmt != null) try { pstmt.close(); } catch (SQLException e) {}
// if (conn != null) try { conn.close(); } catch (SQLException e) {}
// }
// Common SQLState prefixes: '08' = connection error, '23' = integrity
// constraint violation (e.g. duplicate key), '42' = syntax errorSQLException एक checked exception है जो database-specific error information रखती है (SQL state, vendor error code, related exceptions की chain), connections/statements/result sets को error होने पर भी सही से close करना ज़रूरी है।
public List<User> getUsers() {
List<User> users = new ArrayList<>();
String sql = 'SELECT id, name FROM users';
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
users.add(new User(rs.getInt('id'), rs.getString('name')));
}
} catch (SQLException e) {
System.out.println('SQL State: ' + e.getSQLState());
System.out.println('Error Code: ' + e.getErrorCode());
System.out.println('Message: ' + e.getMessage());
SQLException next = e.getNextException();
while (next != null) {
System.out.println('Chained: ' + next.getMessage());
next = next.getNextException();
}
throw new RuntimeException('Users fetch नहीं हुए', e);
}
return users;
}
// try-with-resources automatically close करता है, exceptions पर भी
// Common SQLState prefixes: '08' = connection error, '23' = integrity
// violation, '42' = syntax errorWas this answer clear?