JDBC Exceptions Handling

« Previous Chapter Next Chapter »

Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion.

When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and control is redirected to the nearest applicable catch clause. If no applicable catch clause exists, then the program's execution ends.

JDBC Exception handling is very similar to Java Excpetion handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException.

SQLException Methods:

A SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause.

The passed SQLException object has the following methods available for retrieving additional information about the exception:

Method Description
getErrorCode( ) Gets the error number associated with the exception.
getMessage( ) Gets the JDBC driver's error message for an error handled by the driver or gets the Oracle error number and message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception, or throwable, and its backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify.
printStackTrace(PrintWriter w) Prints this throwable and its backtrace to the print writer you specify.

By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block:


try {
   // Your Code between these braces!!!
catch(Exception ex) {
   // Your exception handling Code between 
   // braces, similar to the exception clause 
   // in a PL/SQL block.
finally {
   // Your must-always-be-executed Code between 
   // braces. Like closing database connection.


Study the following example code to understand the usage of try....catch...finally blocks.


//STEP 1. Import required packages
import java.sql.*;
public class example {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";
   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   public static void main(String[] args) {
   Connection conn = null;
      //STEP 2: Register JDBC driver
      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      Statement stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Friends";
      ResultSet rs = stmt.executeQuery(sql);
      //STEP 5: Extract data from result set
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      //STEP 6: Clean-up environment
   }catch(SQLException se){
      //Handle errors for JDBC
   }catch(Exception e){
      //Handle errors for Class.forName
      //finally block used to close resources
      }catch(SQLException se){
      }//end finally try
   }//end try
   System.out.println("Have A Nice Day");
}//end main
}//end example

Now compile above example:


C:\>javac example.java

it produces following result if there is no problem, otherwise corresponding error would be caught and error message would be displayed:


C:\>java example
Connecting to database...
Creating statement...
ID: 100, Age: 21, First: Sophia, Last: Lomela
ID: 101, Age: 23, First: Katrina, Last: Kane
ID: 102, Age: 24, First: Guru, Last: Morkel
ID: 103, Age: 22, First: Simone, Last: Washer

Try above example by passing wrong database name or wrong username or password and check the result.

« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!