This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried making a ticket using:
Ticket ticket = ForgeChunkManager.requestTicket(this, this.minecraftServer.entityWorld, ForgeChunkManager.Type.NORMAL);
The above code is in my main mod class. I get a NullPointerException when I try to run my mod.
in this case, either this.minecraftServer or this.minecraftServer.entityWorldis null.
try surrounding it with a if statement.
if (this.minecraftServer != null && this.minecraftServer.entityWorld != null){
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
and for the purpose of debugging, I would suggest you separate it in two conditions:
if (this.minecraftServer == null) {
System.out.println("minecraftServer is null");
//or do anything can to warn you
} else if(this.minecraftServer.entityWorld == null) {
System.out.println("entityWorld is null");
//or do anything can to warn you
} else {
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
Unless you can use a debugger to check the values.
But without the full code, it's impossible to know if there's any other error.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I have a com.google.cloud.storage.Blob object. I have been able to download and upload just fine with this object in my java code, but I wanted to check if something exists before starting a process.In a nutshell here is the part of my code giving me issues.
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Function implements BackgroundFunction<GcsEvent> {
public void accept(GcsEvent event, Context context) {
String bucketname = "my_bucket";
String blob_path = "path/to/my/object.jpg";
Storage storage = StorageOptions.newBuilder().setProjectId("my_project_id").build().getService();
Blob b = storage.get(BlobId.of(bucketname, blob_path));
// this is where the null pointer exception occurs
boolean exists = b.exists();
if (exists) {
//do something
}
}
}
Eclipse doesn't seem to catch it in the IDE. and the examples seem to follow this layout as well. Would anyone know what is going on?
I am running on a Linux environment machine. (it failed in cloud function as well).
I am using the Java 11 runtime.
I feel silly. I found out that storage.get(BlobId.of(bucketname, blob_path)); will return null if it can't find the object. instead of using b.exists(), one should check if it is null with if (b != null) { //do stuff }.
This question already has answers here:
How to compare null value from the JsonObject in java
(7 answers)
Closed 3 years ago.
I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:
private JsonObject validateRequestBody(JsonElement requestBody) {
if (!(requestBody instanceof JsonObject)) {
throw new IllegalArgumentException("Request body cannot be case to JSON object");
}
JsonObject bodyObj = requestBody.getAsJsonObject();
System.out.println(bodyObj.get("entityIri").equals(null));
if (bodyObj.get("entityIri") == null) {
System.out.println("null");
throw new IllegalArgumentException("Request body must contain entity IRI");
}
return bodyObj;
}
As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject?
I attach a screenshot from debugging (I cut out irrelevant parts).
Try to use isJsonNull method:
provides check for verifying if this element represents a null value
or not.
if (bodyObj.get("entityIri").isJsonNull()) {
...
}
Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.
This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
Handle Chained Method Calls avoiding NullPointerException - Which is the best way?
Let's imagine this kind of scenario:
3 class Meeting, Room, Projector
A Meeting might have set a Room and it might have a Projector inside them.
Now suppose that I want to know what is the model of the Projector.
The most natural thing is to do something like
Meeting meeting = someMethod();
return meeting.getRoom().getProjector().getModelName();
This code could return the model name of the Projector correctly,
unfortunately this code could also cause an Exeption: an java.lang.NullPointerException in case that one of the class contained into the root class Meeting (or even the Meeting class) is null.
In order to prevent this problem, and get a default value in the worst case we should check the returned value of each call.
Meeting meeting = someMethod();
if (meeting != null) {
Room room = meeting.getRoom();
if (room != null) {
Projector projector = room.getProjector();
if (projector != null) {
return projector.getModelName;
}
}
}
return "No Projector Exist";
The code now is pretty nasty.
What is the best way to deal with this kind of chained method calls avoiding the NullPointerException?
Use Optional:
return Optional.ofNullable(someMethod())
.map(Meeting::getRoom)
.map(Room::getProjector)
.map(Projector::getModelName)
.orElse("No Projector Exist");
As an aside, consider returning Optional or null from your method - having to compare your String to the special hardcoded value to detect the null case is going to get tiresome...
Checking all the null conditions in one if statement also can be done as follows.
So that the code will be much easier to read.
if (meeting != null && meeting.getRoom() != null && meeting.getRoom().getProjector() != null) {
return meeting.getRoom().getProjector().getModelName();
} else {
return "No Projector Exist";
}
The best way is to move the null checks to a private method. So when you give a meeting object, it do the required checks and return the model of the project as a string. So your code will be much simpler and with less complex.
You can catch() the NullPointerException or throw a NoRoomException and a NoProjectorException from your getRoom() and getProjector() methods and catch those.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.
private ArrayList<File> getFiles(String path) {
File f = new File(path);
ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));
return files;
}
thanks for your help
This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist).
In such cases it is always advisable to add some null checks(protective code) in your method.
eg:
if( f != null) { //get the list of files }
may be casue by f.listFiles() return one null array.you can watch the variables in debug model
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
we have a dicussion about that method -
public static AbstractAttribute getAttribute(List<AbstractAttribute> attributes, String name) {
if ((attributes != null) && (name != null) && !name.trim().isEmpty()) {
for (AbstractAttribute attribute : attributes) {
if (attribute.getName().equalsIgnoreCase(name)) {
return attribute;
}
}
}
return null;
}
Is that priori right or not?
IMO there must be checking arguments logic with some exceptions to prevent the "client" wrong using.
So that u must review your code that uses this method in case of error instead of thinking that everything is ok and "list = null" returns the "null" as it does not contain some given key even if list is null though
===========Updated====
there exist 4 general cases for calling that method -
getAttribute(null,null); // returns null
getAttribute(list,null); // returns null
getAttribute(null,name); // returns null
getAttribute(list,name); // may return null if not found
all of them may return null, so how client can understand the difference between different type of calls? He might have made mistake calling method with null argument - and he recieved the null result as if everything ok and attribute just not found in list, but it CANT be found at all.
Hmm... don't know, but i think there must be arg checking...
What you should ask yourself is, which is more useful to a developer?
AbstractAttribute a = getAttribute(null, "name");
a.something(); // Oh no, null pointer.
or
AbstractAttribute a = getAttribute(null, "name"); // Oh no, invalid argument exception.
Your Exception should ALWAYS be as close to the actual problem as possible. If they have a problem with their arguments that fatally interrupts the functionality of the method, then throw an exception! The developer needs to know their mistake and the duty falls to you to make sure it's as clear as possible.
Edit
Yes, you're on the right lines. Your message needs to be specific.
public Object myFunction(String something, String somethingElse) {
// First option - Not so good.
if(something == null || somethingElse == null) {
throw new IllegalArgumentException("Invalid parameters. Can not be null");
}
// Second option - much better.
if(something == null) {
throw new IllegalArgumentException("Something can not be null");
}
if(somethingElse == null) {
throw new IllegalArgumentException("Something else can not be null");
}
}