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
???
Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.
Null dereferencingBecause a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash. In C, dereferencing a null pointer is undefined behavior.
Dereferencing a null pointer is undefined behavior. On many platforms, dereferencing a null pointer results in abnormal program termination, but this is not required by the standard.
Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With