1. 程式人生 > 實用技巧 >JAVA異常的不正確處理方式

JAVA異常的不正確處理方式

最近收到一個求助資訊,異常堆疊如下:

java.lang.RuntimeException: FF1C1005
	at test_ssh.sftp.Pool.get(Pool.java:25) ~[test-ssh-0.0.1-SNAPSHOT.jar:na]
	... 116 common frames omitted
Caused by: java.lang.NullPointerException: null
	at test_ssh.sftp.Pool.get(Pool.java:23) ~[test-ssh-0.0.1-SNAPSHOT.jar:na]

從堆疊資訊看就是一個NPE,其他什麼也看不出,再看程式碼(簡化的示例程式碼):

package test_ssh.sftp;

import java.util.concurrent.ConcurrentHashMap;
import com.trilead.ssh2.Connection;

public class Pool {
    private static ConcurrentHashMap pool = new ConcurrentHashMap();

    public synchronized static Connection get(String host, int ftpport) {
        Connection connection = pool.get(host) == null ? connect(host, ftpport) : pool.get(host);
        try {
            connection.ping();
        } catch (Exception e) {
            throw new RuntimeException("FF1C1005", e);
        }
        return connection;

    }

    private static Connection connect(String host, int ftpport) {
        Connection connection = new Connection(host, ftpport);
        try {
            connection.connect();
        } catch (Throwable e) {
            return null;
        }
        return connection;

    }

}

程式碼沒有在適當的點丟擲異常,把原始異常資訊丟了~先修正下程式碼,該拋的異常丟擲來:

public synchronized static Connection get(String host, int ftpport) {
        Connection connection = pool.get(host) == null ? connect(host, ftpport) : pool.get(host);
        try {
            connection.ping();
        } catch (Exception e) {
	    e.printStackTrace();
            throw new RuntimeException("FF1C1005", e);
        }
        return connection;
}

private static Connection connect(String host, int ftpport) {
        Connection connection = new Connection(host, ftpport);
        try {
            connection.connect();
        } catch (IOException e) {
            throw e;
        }
        return connection;

    }

}