English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Exception handling allows you to handle abnormal situations in a controlled manner, such as errors defined by the program.
When an abnormal situation occurs, an exception will be triggered. The word 'throw' means that the current program execution stops and the control is redirected to the nearest applicable catch clause. If there is no applicable catch clause, the execution of the program ends.
JDBC exception handling is very similar to Java exception handling, but for JDBC, the most common exceptions you need to handle are java.sql.SQLException.
SQLException can occur in both drivers and databases. When such an exception occurs, an SQLException object of type is passed to the catch clause.
The SQLException object passed in has the following methods available for retrieving other information about the exception-
Method | Description |
---|---|
getErrorCode() | Get the error number associated with the exception. |
getMessage() | Get the JDBC driver error message, which is handled by the driver, or get the Oracle error number and message for database errors. |
getSQLState() | Get the XOPEN SQLstate string. For JDBC driver errors, this method does not return any useful information. For database errors, it will return a five-digit xopensqlstate code. This method can return null. |
getNextException() | Get the next Exception object in the exception chain. |
printStackTrace() | Print the current exception or callable exception, and backtrack it to the standard error stream. |
printStackTrace(PrintStream s) | Print this disposable object and its stack trace to the specified print stream. |
printStackTrace(PrintWriter w) | Print this one-time file and backtrack it to the specified print writer. |
By utilizing the information provided by the Exception object, you can catch exceptions and continue executing the program appropriately. This is the general form of the try block-
try { // Your exception code between these braces!!! } catch(Exception ex) { // Your exception handling code between these two // Braces, similar to the exception clause // In PL / in the SQL block. } finally { // The code you must always execute between these two //Braces. Just like closing the database connection. }
Study the following example code to understandtry....catch...finallyUsage of the block.
//Step1.Import the required software packages import java.sql.*; public class JDBCExample { // JDBC driver program 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; try{ //Step2Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //Step3Establish connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //Step4Execute query System.out.println("Creating statement..."); Statement stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); //Step5Extract data from the result set while(rs.next()){ //Search by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display value System.out.print("ID: ", + id; System.out.print(", Age: ", + age; System.out.print(", First: ", + first); System.out.println(", Last: ", + last); } //Step6Clean up environment rs.close(); stmt.close(); conn.close(); catch(SQLException se){ //Handling JDBC error se.printStackTrace(); Handling Class.forName error //e.printStackTrace(); finally{ } //Finally block to prevent resource from being blocked try{ if(conn!=null) conn.close(); catch(SQLException se){ se.printStackTrace(); } }//End try System.out.println("Goodbye!"); }//End main }//End JDBCExample
Now, let's compile the above example as follows:
C:\>javac JDBCExample.java C:\>
RuntimeJDBCExampleIf there is no problem, it will produce the following result, otherwise it will catch the corresponding error and display the error message-
C:\>java JDBCExample Connecting to database... Creating statement... ID: 10, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 3, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>
Try the above example by passing an incorrect database name or an incorrect username or password, and then check the result.