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();
}
}