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.

Copyfinally {
  if (channelTarget != null) {
       channelTarget.exit();     
       channelTarget.disconnect();  
  }
  if (sessionTarget != null ) {
       sessionTarget.disconnect();  
  }
}
Answer from Abimaran Kugathasan on Stack Overflow
🌐
Quora
quora.com › How-do-I-avoid-dereferencing-null-pointers-in-Java
How to avoid dereferencing null pointers in Java - Quora
Answer (1 of 2): I love the way you put it, brings back memories of switching from C to Java some 20 years ago :) Anyway, let’s get to it: You prevent NullPointerException by testing and validation. Sometimes we also use reflection to automate testing. Testing When I write a method, I immedia...
🌐
AWS
docs.aws.amazon.com › codeguru › detector-library › java › null-pointer-dereference
Null pointer dereference | Amazon Q, Detector Library
1private Double nullCheckPointerNoncompliant(@Nullable Double digit) { 2 // Noncompliant: avoids null checks before dereferencing the pointer.

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.

Copyfinally {
  if (channelTarget != null) {
       channelTarget.exit();     
       channelTarget.disconnect();  
  }
  if (sessionTarget != null ) {
       sessionTarget.disconnect();  
  }
}
Answer from Abimaran Kugathasan on Stack Overflow
Top answer
1 of 2
10

So if you throw an exception on your first line, your variable will not be assigned to a File, and will retain it's previous value (null if not formerly assigned). Your exception is caught, and then you continue to use that unassigned variable. Hence the warning. See the commented code below.

try {
        fileFile = // exception thrown. Variable not assigned
} catch (URISyntaxException | NullPointerException e) {
        // exception caught
    }
    finally {
       // unassigned variable used here...
        if (fileFile.getPath()!= null){
            strPathName = fileFile.getPath();
        }
        if (fileFile.getName() != null){
            strFileName = fileFile.getName();
        }
    }  

I would rather scope and use the variable within the try block, if at all practical. In your finally block, you need to be as careful as you can, since you could have come to it from most anywhere in your try block.

As an aside, this:

Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();

will cause you enormous problems if you do get an NPE. Which of the above resolved to null ? I would perhaps be more explicit, such that you can check for nulls from each invocation and unambiguously determine which invocation gave you a null. Tiresome ? Unfortunately so.

2 of 2
2

A "null pointer dereference" is computer speak for trying to call a method on a null value. It's a little more complicated, but you said you were a novice, so I wanted to keep it simple.

Let's see an example:

String s = null;
s = s.toUpperCase();

This is a simple example of what a null pointer dereference is. s is a null reference (its value is null), when we derefrence is (get the value of it) we have null, when we call toUpperCase() on null, something goes horribly wrong because null doesn't have any methods, at all! Java throws a NullPointerException to be specific.


Now, back to your code, because fileFile is assigned in the try-block I assume it was set to null before it to avoid Java yelling about an uninitialized variable. (This is all fine and correct.) In this try-block, if any of the exceptions for your catch-block occur it will stop the try-block (meaning fileFile will not get a new value, meaning it will still be null).

Now you'll notice the warning is possible null pointer dereference. That means it won't necessarily be null, but could be! (In my above example, it's always a null pointer dereference for comparison.) Specifically, if the catch catches an exception it will be null.

To be clear, the issue is this: fileFile.getPath(). It's like saying it might be null.getPath(), gross. It looks like you were trying to avoid the null pointer issue, what you should have done was if (fileFile != null) { instead. Then inside of the if do what you want.


Also, because it seems like you included it to avoid this warning, I would seriously remove the NullPointerException from the catch-block. That's not helping you avoid the warning. If you want me to explain more why it's bad you can leave a comment and I will, otherwise just take my word for it, it's not helping you.

🌐
Wikipedia
en.wikipedia.org › wiki › Null_pointer
Null pointer - Wikipedia
2 days ago - Dereferencing it raises an external OS exception which is mapped onto a Pascal EAccessViolation exception instance if the System.SysUtils unit is linked in the uses clause. In Java, access to a null reference (null) causes a NullPointerException (NPE), which can be caught by error handling ...
🌐
Coderanch
coderanch.com › t › 563727 › java › explain-null-pointer-dereference
please explain null pointer dereference [Solved] (Java in General forum at Coderanch)
January 6, 2012 - Dereferencing a reference means accessing the object it's referencing/pointing to. Most commonly, that means accessing a property or calling a method on the object. So "dereferencing a null pointer" means trying to do something to the object that it's pointing to.
Find elsewhere
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › EXP01-J.+Do+not+use+a+null+in+a+case+where+an+object+is+required
EXP01-J. Do not use a null in a case where an object is required | CERT Secure Coding
One valid use of the cardinality() method is to determine how many objects in the collection are null. However, because membership in the collection is checked using the expression obj.equals(elt) , a null pointer dereference is guaranteed whenever obj is null and elt is not null.
🌐
Mayhem Security
mayhem.security › blog › what-is-null-pointer-dereference
What Is Null Pointer Dereference? | Mayhem
June 1, 2022 - There are a few ways to avoid null pointer dereferences. One is to use a language that does not allow them, such as Java. Another is to always check pointers for NULL before dereferencing them.
🌐
CodingTechRoom
codingtechroom.com › question › understanding-dereferencing-null-pointer
Understanding Dereferencing a Possible Null Pointer in Programming - CodingTechRoom
Solution: Implement checks like if(ptr != nullptr) to avoid dereferencing null pointers. Mistake: Assuming a pointer will always point to valid memory after being declared. Solution: Initialize pointers properly and handle cases where they may be set to null. ... Learn how to effectively use JPQL IN queries with enum values in Java Persistence API including examples and common pitfalls.
🌐
Snyk Learn
learn.snyk.io › home › security education › what is a null dereference? | tutorial & examples
What is a null dereference? | Tutorial & examples | Snyk Learn
August 15, 2024 - In languages that use pointers, ... use pointers, such as Java and Python, null dereferences may not cause the program to crash, but can still lead to runtime errors ......
🌐
Stack Overflow
stackoverflow.com › questions › 79455327 › dereferencing-null-pointer
java - Dereferencing null pointer? - Stack Overflow
Because nothing about throwing or seeing an NPE would cause one to say 'dereferencing a null pointer?'. It's called NullPointerException, not NullDereferenceException after all.
🌐
Medium
medium.com › @chanibonner › a-beginners-guide-to-null-pointer-dereference-attacks-d3618cc8a493
A Beginner’s Guide to Null Pointer Dereference Attacks | by Chani Bonner | Medium
February 25, 2024 - That’s what happens when a pointer has a null value. Let’s see what happens next. Now that you have an idea of what a NPD is, imagine for a minute someone tries to dereference a null pointer in the same way they would a pointer that contains a valid memory address.
🌐
Medium
medium.com › swlh › one-way-to-sidestep-potential-null-pointer-warning-in-java-ffef431394a8
One Way to Sidestep Potential Null Pointer Warning in Java | by Alonso Del Arte | The Startup | Medium
September 15, 2020 - Test-driven development is also a big help in that department. A null pointer exception in a development context is then just a part of the process, not something to fear, much less hate. Still, the “dereferencing possible null pointer” warning can be annoying at times.
🌐
Fortify
vulncat.fortify.com › en › detail
Software Security | Null Dereference - Fortify Taxonomy
Dereference-after-check errors occur when a program makes an explicit check for null, but proceeds to dereference the pointer when it is known to be null. Errors of this type are often the result of a typo or programmer oversight. A dereference-after-store error occurs when a program explicitly sets a pointer to null and dereferences it later...
🌐
OWASP Foundation
owasp.org › www-community › vulnerabilities › Null_Dereference
Null Dereference | OWASP Foundation
CWE-476: NULL Pointer Dereference: A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
🌐
Sonar Community
community.sonarsource.com › rules and languages › report false-positive / false-negative...
SonarQube - Null Pointer Dereference Issue - Report False-positive / False-negative... - Sonar Community
June 26, 2018 - Hi! I was fixing some issues gathered by SonarQube when I stumbled upon the following issue: “SonarQube violation: Possible null pointer dereference in ___ due to return value of called method” This error was found in the following code: ... else if (foo.list().length > 0) { ... } I attempted to resolve this by rewriting as: ... else if (null != foo.list() && foo.list().length > 0) { ... } foo is an instance of the File class in Java, and is directly instantiated through new File(...) The ...
🌐
GitHub
github.com › apache › netbeans › issues › 6106
Wrong Warning - Dereferencing possible null pointer · Issue #6106 · apache/netbeans
June 21, 2023 - Java[ci] enable extra Java tests (java.completion, java.source.base, java.hints, refactoring.java, form)[ci] enable extra Java tests (java.completion, java.source.base, java.hints, refactoring.java, form)hintskind:bugBug report or fixBug report or fix ... NetBeans warns about dereferencing possible null pointer where I'm somewhat sure that no NPE can happen at all, because null-checks are available already.
Author   apache