什么是取消引用可能的空指针?

新手上路,请多包涵

我正在为 SFTPNetBeans 制作一个程序。

我的代码的一部分:

 com.jcraft.jsch.Session sessionTarget = null;
com.jcraft.jsch.ChannelSftp channelTarget = null;
try {
       sessionTarget = jsch.getSession(backupUser, backupHost, backupPort);
       sessionTarget.setPassword(backupPassword);
       sessionTarget.setConfig("StrictHostKeyChecking", "no");
       sessionTarget.connect();
       channelTarget = (ChannelSftp) sessionTarget.openChannel("sftp");
       channelTarget.connect();

       System.out.println("Target Channel Connected");
       } catch (JSchException e) {
            System.out.println("Error Occured ======== Connection not estabilished");
            log.error("Error Occured ======== Connection not estabilished", e);
       } finally {
            channelTarget.exit();     // Warning : dereferencing possible null pointer
            channelTarget.disconnect();  // Warning : dereferencing possible null pointer
            sessionTarget.disconnect();  // Warning : dereferencing possible null pointer
        }

我收到警告 dereferencing possible null pointer ,我该如何解决这些警告???我在哪里可以断开我的 SessionChannel ???

原文由 earthmover 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 385
2 个回答

sessionTarget = jsch.getSession(backupUser, backupHost, backupPort); Here in this line, getSession() method can throw an Exception, and hence the variables sessionTarget and channelTarget will be null, and in在 finally 块中,您正在访问那些可能导致空指针异常的变量。

为避免这种情况,在 finally 块中,在访问变量之前检查是否为 null。

 finally {
  if (channelTarget != null) {
       channelTarget.exit();
       channelTarget.disconnect();
  }
  if (sessionTarget != null ) {
       sessionTarget.disconnect();
  }
}

原文由 Abimaran Kugathasan 发布,翻译遵循 CC BY-SA 4.0 许可协议

这意味着:如果您的 channelTargetsessionTarget 在您的 finally 块中为空怎么办?检查它们是否为空以避免警告。

原文由 sadhu 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题