📅  最后修改于: 2020-11-13 04:35:55             🧑  作者: Mango
异常处理使您能够以受控方式处理特殊情况,例如程序定义的错误。
发生异常情况时,将引发异常。抛出这个词意味着当前程序停止执行,并且控件被重定向到最近的适用catch子句。如果不存在适用的catch子句,则程序的执行结束。
JDBC异常处理与Java异常处理非常相似,但是对于JDBC,您要处理的最常见的异常是java.sql.SQLException。
在驱动程序和数据库中都可能发生SQLException。发生此类异常时,会将SQLException类型的对象传递给catch子句。
传递的SQLException对象具有以下可用于检索有关异常的其他信息的方法-
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 it’s 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 it’s backtrace to the print writer you specify. |
通过利用Exception对象提供的信息,您可以捕获异常并适当地继续执行程序。这是try块的一般形式-
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
研究以下示例代码,以了解try …. catch … finally块的用法。
//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 data from result set
while(rs.next()){
//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
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
现在,让我们编译以上示例,如下所示:
C:\>javac JDBCExample.java
C:\>
当您运行JDBCExample时,如果没有问题,它将产生以下结果,否则将捕获相应的错误并显示错误消息-
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:\>
通过传递错误的数据库名称或错误的用户名或密码来尝试上述示例,然后检查结果。