Open In App

JDBC Exception Handling

Last Updated : 01 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JDBC is a Java API that allows interaction with databases. JDBC exceptions like SQLException commonly occur due to connection issues, SQL syntax errors or data type mismatches and are handled using standard Java exception handling.

Why is JDBC Exception Handling Important?

When we communicate  with databases,some problems occur like:

  • Invalid SQL syntax bad query
  • Connection time out problem 
  • Wrong data types mentioned
  • miss  database drivers

The below code describes how we handle exceptions.

Java
try {
//Risky code is define in that block
}
catch(Exception ex) {
//Exception handling code define hare

}
finally {
            // This block always used for closing resource
            }

Types of JDBC Exceptions in Java

1. SQLException: it is a Checked Exception. it is occur when we have defined wrong sql syntax like Incorrect SQL syntax, Invalid table or column name.

Incorrect SQL syntax:

Example:

SELECT * FORM person; // 'FROM' is misspelled

Error:

java.sql.SQLSyntaxErrorException: Syntax error in SQL statement

Invalid table or column names

Example:

SELECT * FROM perso; // 'person' is misspelled

Error:

java.sql.SQLSyntaxErrorException: Table 'person' doesn't exist

2. ClassNotFoundException: It is a checked exception. This occur when the JDBC driver class is not found.

Example:

Class.forName("com.mysql.cj.jdbc.Driver");

If the MySQL driver is missing from the classpath.

3. SQLTimeoutException: It is a subclass of SQLException. It occurs when a query takes too long and exceeds the configured timeout limit.

Example:

statement.setQueryTimeout(seconds)

Example: The below-described code describes how to handle Jdbc Exception.

Java
package org.vishnu;
import java.sql.*;
import javax.sound.midi.Soundbank;

public class App {
    public static void main(String[] args) throws Exception
    {
        // fetching data from database
        String email = "gaurav@gmail.com";
        // we have use try with resourse for  automatically close JDBC resources
        try {
            // Load and ragister the driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (
                // create connection
                Connection con
                = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/jdbc_db",
                    "root", "password");
                // execute dynamic query
                PreparedStatement ps = con.prepareStatement(
                    "select * from ragister");
                // store the result
                ResultSet rs = ps.executeQuery();
                // process the result
            ) {
                while (rs.next()) {
                    String name1 = rs.getString("name");
                    System.out.println("name->" + name1);
                    String email1 = rs.getString("email");
                    System.out.println("email->" + email1);
                    String poss = rs.getString("possword");
                    System.out.println("poss->" + poss);
                    String gen = rs.getString("gender");
                    System.out.println("gender->" + gen);
                    String city1 = rs.getString("city");
                    System.out.println("city->" + city1);
                    System.out.println(
                        "------------------------");
                }
            }
        }
        catch (SQLSyntaxErrorException se) {
            System.err.println("Error in sql syntax: "
                               + se.getMessage());
        }
        catch (SQLTimeoutException te) {
            System.err.println("Query Time Expire: "
                               + te.getMessage());
        }
        catch (ClassNotFoundException e) {
            System.err.println("jdbc driver not found.");
        }
        catch (Exception e) {
            System.err.println("Unexpected error: "
                               + e.getMessage());
        }
    }
}

Output:

jd
output

Explanation

  • Connects to a MySQL database named jdbc_db using JDBC.
  • Uses try-with-resources to automatically close JDBC resources.
  • Loads the MySQL JDBC driver using Class.forName.
  • Establishes a connection using DriverManager.getConnection.
  • Prepares and executes a SQL query to select all records from the ragister table.
  • Iterates through the ResultSet to print values of name, email, possword, gender and city.
  • Catches and handles SQLSyntaxErrorException for SQL syntax issues.
  • Catches and handles SQLTimeoutException if the query exceeds time limits.
  • Catches and handles ClassNotFoundException if the JDBC driver is missing.
  • Catches any other unexpected exceptions.

Best Way  for JDBC Exception Handling

  • Always close resources using try-with-resources.
  • Avoid exposing DB details in production error messages.
  • Use meaningful messages in catch blocks.
  • Don't catch generic Exception unless necessary

Article Tags :