JDBC - Exceptions Handling



Exception taking care of enables you to deal with remarkable conditions, for example, program-characterized mistakes in a controlled fashion.

When an exemption condition happens, a special case is tossed. The term tossed implies that present program execution stops, and the control is diverted to the closest appropriate catch proviso. On the off chance that no appropriate catch provision exists, at that point the program's execution ends.

JDBC Exception taking care of is fundamentally the same as the Java Exception taking care of however for JDBC, the most well-known special case you'll manage is java.sql.SQLException.

SQLException Methods

An SQLException can happen both in the driver and the database. At the point when such a special case happens, an object of sort SQLException will be passed to the catch clause.

The passed SQLException object has the accompanying techniques accessible for recovering extra data about the exemption −

Method Description
getErrorCode( ) Gets the mistake number related with the exception.
getMessage( ) Gets the JDBC driver's mistake message for a blunder, dealt with by the driver or gets the Oracle blunder number and message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver mistake, no valuable data is come back from this technique. For a database blunder, the five-digit XOPEN SQLstate code is returned. This strategy can return null.
getNextException( ) Gets the following Exception object in the special case chain.
printStackTrace( ) Prints the present special case, or throwable, and it's backtrace to a standard blunder stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify.
printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the print author you specify.

By using the data accessible from the Exception object, you can get a special case and proceed with your program properly. Here is the general type of an attempt square −

try { 

//Your hazardous code goes between these wavy braces!!! 

} 

catch(Exception ex) { 

//Your special case taking care of code goes between these  

//wavy supports, like the special case condition  

//in a PL/SQL block. 

} 

finally { 

//Your must-dependably be-executed code goes between these  

//wavy supports. Like shutting database connection. 

}

Example

Study the accompanying precedent code to comprehend the utilization of try....catch...finally blocks.

//STEP 1. Import required packages 

import java.sql.*; 

public class JDBCExample { 

//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; 

try{ 

//STEP 2: Register JDBC driver 

Class.forName("com.mysql.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 Employees"; 

ResultSet rs = stmt.executeQuery(sql); 

//STEP 5: Extract information from result set 

while(rs.next()){ 

//Retrieve by segment 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 

rs.close(); 

stmt.close(); 

conn.close(); 

}catch(SQLException se){ 

//Handle mistakes for JDBC 

se.printStackTrace(); 

}catch(Exception e){ 

//Handle mistakes for Class.forName 

e.printStackTrace(); 

}finally{ 

//at long last square used to close resources 

try{ 

if(conn!=null) 

conn.close(); 

}catch(SQLException se){ 

se.printStackTrace(); 

}//end at long last try 

}//end try 

System.out.println("Goodbye!"); 

}//end main 

}//end JDBCExample

Now, let us assemble the above precedent as pursues −

C:\>javac JDBCExample.java 

C:\>

When you run JDBCExample, it creates the accompanying outcome if there is no issue, generally the comparing mistake would be gotten and blunder message would be shown −

C:\>java JDBCExample 

Connecting to database... 

Creating statement... 

ID: 100, Age: 18, First: Zara, Last: Ali 

ID: 101, Age: 25, First: Mahnaz, Last: Fatma 

ID: 102, Age: 30, First: Zaid, Last: Khan 

ID: 103, Age: 28, First: Sumit, Last: Mittal 

C:\>

Try the above precedent by passing incorrectly database name or wrong username or secret phrase and check the result.







© Javacodegeeks © 2019 - 2019
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3