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,其他什么也看不出,再看代码(简化的示例代码):

 1 package test_ssh.sftp;
 2 
 3 import java.util.concurrent.ConcurrentHashMap;
 4 import com.trilead.ssh2.Connection;
 5 
 6 public class Pool {
 7     private static ConcurrentHashMap<String, Connection> pool = new ConcurrentHashMap<String, Connection>();
 8 
 9     public synchronized static Connection get(String host, int ftpport) {
10         Connection connection = pool.get(host) == null ? connect(host, ftpport) : pool.get(host);
11         try {
12             connection.ping();
13         } catch (Exception e) {
14             throw new RuntimeException("FF1C1005", e);
15         }
16         return connection;
17 
18     }
19 
20     private static Connection connect(String host, int ftpport) {
21         Connection connection = new Connection(host, ftpport);
22         try {
23             connection.connect();
24         } catch (Throwable e) {
25             return null;
26         }
27         return connection;
28     }
29 }

 

代码没有在适当的点抛出异常,把原始异常信息丢了~先修正下代码,该抛的异常抛出来:

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;

    }

}

 

重新打包运行,然后用新开会话运行tail -f 命令追踪日志,准备查看异常信息,然而并未如预期看到异常信息~难道IO被重定向了? 停止服务,在控制终端下重新启动服务,果然日志刷新到标准输出了:

java.io.IOException: There was a problem while connecting to 10.246.186.37:10022
at com.trilead.ssh2.Connection.connect(Connection.java:843)
... 119 more
Caused by: java.io.IOException: Cannot negotiate, proposals do not match.
at com.trilead.ssh2.transport.KexManager.handleMessage(KexManager.java:399)

**Linux会话使用技巧**

服务端程序通常会以守护进程方式启动,不能随意重启,那如果想查看程序输出到stdout(通常不会这么做,但不排除意外)的信息怎么办呢?两个办法:

[1]tail -f /proc/PID/fd/1 这里1是标准输出,当然也可以是2 stderr
[2]sudo strace -p PID -e write

  

posted @ 2020-12-17 10:59  七彩代码  阅读(868)  评论(0)    收藏  举报