5.
import java.sql.*;
import java.util.*;
public class UnifiedException
{
private HashMap ht;
public UnifiedException(){
ht = new HashMap();
extractDataFromDatabase();
//ht.put("/ by zero","发生了除数为零异常");
//ht.put(null,"发生了空指针异常");
}
public void extractDataFromDatabase(){
String url = "jdbc:odbc:myDSN";
String query = "SELECT name,note FROM dictionary";
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection (url, "sa", "");
stmt = con.createStatement ();
rs = stmt.executeQuery (query);
//从数据库中提取相应的异常提示信息
while (rs.next()) {
String tem = rs.getString(1);
if(tem.equals("null")){
ht.put(null,rs.getString(2));
}
else{
ht.put(tem,rs.getString(2));
}
}
}
catch (SQLException ex) {System.out.println ("发生SQL异常"); }
catch (Exception ex) {ex.printStackTrace ();}
finally{
try{
if (rs!=null) rs.close();
if (stmt!=null) stmt.close();
if (con!=null) con.close();
}
catch (SQLException ex) {}
}
}
public void dealException(Exception e){
String str = e.getMessage();
System.out.println((String)ht.get(str));
}
public static void main(String[] args)
{
int a,b,c;
try{
a=67; b=0;
//c=a/b;
throw new NullPointerException();
}
catch(Exception e){
new UnifiedException().dealException(e);
}
}
}
6.
public class ExeSql{
public boolean execSql(String sqlStr){
String[] sql=new String[1];
sql[0] =sqlStr;
return execSql(sql);
}
public boolean execSql(String[] sql){
if (sql == null)
{
return false;
}
else if (sql.length == 0)
{
return false;
}
Connection con =null;
Statement state=null ;
int i=0;
try{
con = getConnection();
state =con.createStatement();;
con.setAutoCommit(false);
for(i = 0 ;i<sql.length;i++){
state.executeUpdate(sql[i]);
}
con.commit();
con.close();
con = null;
return true;
}
catch(Exception e){
try{
con.rollback();
if (i<sql.length)
{
System.out.println("-------------------");
System.out.println("出现错误:"+sql[i]);
System.out.println("-------------------");
e.printStackTrace();
}
}
catch(SQLException ee){
}
return false;
}
finally{
try{
state.close();
con.close();
}
catch(Exception e){
}
}
}
private Connection getConnection() {
//得到同数据库相连接的各种方法
}
}