An SQLException in Java is thrown when something goes wrong with database access using JDBC (Java Database Connectivity).
🔥 Common causes include:
- Invalid database URL or credentials.
- Syntax errors in SQL queries.
- Trying to access non-existent tables/columns.
- Network issues between application and DB server.
- Trying to insert duplicate keys (violating constraints).
- Forgetting to close connections leading to resource exhaustion.
✅ How to Handle SQLException in Java
You can handle it using try-catch blocks and examine:
e.getMessage()→ Describes the error.e.getErrorCode()→ Vendor-specific error code.e.getSQLState()→ SQL state as per ANSI SQL standard.
🧪 Example: Handling SQLException
import java.sql.*;
public class SQLExceptionExample {
public static void main(String[] args) {
Connection conn = null;
try {
// Load JDBC driver (optional in modern Java)
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to database
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "wrongpassword"
);
// Execute a query
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM non_existing_table");
} catch (SQLException e) {
System.out.println("SQLException occurred!");
System.out.println("Message: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("ErrorCode: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found: " + e.getMessage());
} finally {
// Close connection
try {
if (conn != null) conn.close();
} catch (SQLException e) {
System.out.println("Failed to close connection: " + e.getMessage());
}
}
}
}
✅ Best Practices:
- Always use try-with-resources to auto-close
Connection,Statement, andResultSet. - Log SQL exceptions properly.
- Avoid revealing full SQL errors to users — use generic messages in production.