Handle SQL Exceptions example

This is an example of how to handle SQL Exceptions in Java. Handling SQL Exceptions implies that you should:

  • Load the JDBC driver, using the forName(String className) API method of the Class. In this example we use the Oracle JDBC driver.
  • Create a Connection to the database. Invoke the getConnection(String url, String user, String password) API method of the DriverManager to create the connection.
  • Catch the SQLException and check the Exception message.
  • Check the reason of the exception, the vendor-specific codes for the error and the SQLState for this SQLException, with getMessage(), getErrorCode(), getSQLState() API methods of SQLException.
  • In order to execute code based on the specific error code check the driver used for the JDBC connection. Get the DatabaseMetaData of the Connection, with getMetaData() API method of Connection and then the Driver name, with getDriverName() API method of DatabaseMetaData.
  • If the exception is chained process the next exception in the chain, with getNextException() API method of SQLException.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLException {
  public static void main(String[] args) {

    Connection connection = null;
    try {

  // Load the Oracle JDBC driver

  String driverName = "oracle.jdbc.driver.OracleDriver";


  // Create a connection to the database

  String serverName = "localhost";

  String serverPort = "1521";

  String sid = "mySchema";

  String url = "jdbc:oracle:thin:@" + serverName + ":" + serverPort + ":" + sid;

  String username = "username";

  String password = "password";

  connection = DriverManager.getConnection(url, username, password);


  System.out.println("Successfully Connected to the database!");

    } catch (ClassNotFoundException e) {

  System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {

  while (e != null) {

    // the reason for the exception

    String message = e.getMessage();

    // vendor-specific codes for the error 

    int errorCode = e.getErrorCode();

    String sqlState = e.getSQLState();

    // To execute code based on the specific error code we should first check the driver used

    String driverName;


    try {

  driverName = connection.getMetaData().getDriverName();

  if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) {

    // Process error specific to Oracle database ...


    } catch (SQLException e1) {

    System.out.println("Could not retrieve database metadata " + e1.getMessage());


    // The exception may have been chained; process the next exception in the chain

    e = e.getNextException();





Successfully Connected to the database!

This was an example of how to handle SQL Exceptions in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button