如何以自定义方式处理NullPointerException

时间:2014-03-12 07:29:13

标签: java oracle

我正在使用oracle连接来处理一些文件。我有一个xml文件提供了一些条件,无论是true还是false.Upon将连接oracle连接。所以我能够处理多少,但问题是,当条件为false时,连接被关闭但是调用连接的类正在获取NULLPointerException。我必须使用正确的消息来处理Nullpointer ...我正在发布代码...

提供连接......

   try {
        String s;
        if ("DB2".equalsIgnoreCase(db)) {
            s = "jdbc:db2://" + host + ':' + port + '/' + sid;
            Class.forName("com.ibm.db2.jcc.DB2Driver");
            conn = DriverManager.getConnection(s, user, pwd);
        } else if ("ORACLE".equalsIgnoreCase(db)) {
            if(isProcessed.equalsIgnoreCase("true")){
            s = "jdbc:oracle:thin:@//" + host + ':' + port + '/' + sid;
            //s = "jdbc:oracle:thin:@" + host + ":" + port + ":" + sid;
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(s,user,pwd);
            }else{
                try{

                    conn.close();
                }catch(Exception e){
                    System.out.println("Aborted by user");
                }

            }
        } else {
            throw new Exception("Error : Unsupported DataBase : " + db);
        }
    } catch (ClassNotFoundException e) {
        throw new Exception("Unable to load Driver class ", e);
    }
    return conn;
}

正在调用连接的类......

public class HuaGPRSFileExecutor extends FileExecutor {

protected void processFile(PathHandler output, FileStatus fileStatus) throws Exception {
    LinkedHashMap<String, Object> record = HuawieGPRSParser.persefile(fileStatus);
    for (String eventName : record.keySet()) {
        if (eventName == null || "null".equals(eventName)) continue;
        ArrayList<LinkedHashMap<String, Object>> events = (ArrayList<LinkedHashMap<String, Object>>) record.get(eventName);
        try {
            Connection conn = getConnection();
            new HuawieGPRSCDRHandler().populateDB(eventName, events, fileStatus, conn);
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            new HuawieGPRSCDRHandler().generateFile(output, events, fileStatus);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

 try {
            Connection conn = getConnection();
            if(conn== null)
              {

      //You can either print the message saying 

//连接为空或触发自定义
//如果你需要通过异常

处理它的例外
               }
            else{

            new HuawieGPRSCDRHandler().populateDB(eventName, events, fileStatus, conn);

                }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }