I am making a program for SFTP in NetBeans.

Some part of My code:

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
        }

I'm getting warning dereferencing possible null pointer, how can I resolve these warnings??? Where I can disconnect my Session and Channel???

有帮助吗?

解决方案

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 the finally block, you are accessing those variables, which may cause null pointer exception.

To avoid this, in the finally block check for null before accessing the variable.

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

其他提示

That means: what if your channelTarget and sessionTarget are null in your finally block? Check them for null to avoid the warning.

I think netbeans is just trying to warn you that these may be null which may not be necasarilly true. You can choose to disable the warnings though. Just place your cursor on the warning press ALT+ENTER and choose from the choices even to disable the warnings.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top