简体   繁体   English

有时会抛出NullPointerException,有时不会。 怎么修?

[英]Sometimes throw NullPointerException, and sometimes not. How to fix?

Here's an excerpt of the init of the object: 这是对象初始化的摘录:

    ...
            Rectangle b1 = tenBullets.getBounds();
    ...

Here's the getBounds() method: 这是getBounds()方法:

public Rectangle getBounds() {
    return new Rectangle(x, y, 200, 25);
}

And here is the console message: 这是控制台消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at test.game.Board.checkCollisions(Board.java:75)
at test.game.Board.actionPerformed(Board.java:53)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Board.java:75 is when the getBounds() method is called. Board.java:75是调用getBounds()方法时。 Sometimes the exception is thrown, and 1 out of the 10th time it's not. 有时会引发异常,而第十次异常中不会抛出异常。 Any fixes? 有任何解决办法吗?

The NullPointerException is thrown because tenBullets is null when that method is called - and you're trying to invoke a method on a null object (which isn't possible, and leads to the exception). 抛出NullPointerException是因为tenBullets该方法时tenBulletsnull ,并且您试图在null对象上调用方法(这是不可能的,并导致异常)。

In order to fix this, you need to do one of two things: 为了解决此问题,您需要执行以下两项操作之一:

  1. Change the preceding behaviour, so that tenBullets is always assigned a value before you call getBounds() on it. 更改前面的行为,以便在对tenBullets调用getBounds()之前始终tenBullets分配一个值。 This is the option to choose is tenBullets should never be null at this point. 这是可以选择的选项,因为tenBullets在这一点上绝对不能为null。
  2. Make the code in the question tolerant of null - check if (tenBullets == null) , and take some alternative action if this is true. 使问题容忍代码中的代码为if (tenBullets == null)检查if (tenBullets == null) ,如果为true,则采取一些替代措施。 This is the option to choose if null might well be a sensible value (perhaps it may or may not be initialised); 这是一个选择,选择null是否很可能是一个明智的值(也许可以初始化也可以不初始化); if so, you have to deal with that eventuality. 如果是这样,您必须应对这种情况。

Without understanding either the intent or the context of the code, it's impossible to give concrete recommendations. 如果不了解代码的意图或上下文,就不可能给出具体的建议。 However, if tenBullets is a field (as opposed to a local variable), consider whether it ever makes sense for it to be unset (or modified); 但是,如果tenBullets是一个字段(而不是局部变量),考虑是否曾经有意义它被取消设置(或修改); and if not, declare it final . 如果不是,则将其声明为final This will guarantee that it is initialised within the constructor and holds that value consistently. 这将确保它在构造函数中初始化并保持该值一致。

In general, reducing the number of mutable fields/variables makes it much easier to reason about a program, because you need to be less aware of what state it may or may not be in at the time of execution. 通常,减少可变字段/变量的数量使对程序的推理变得容易得多,因为您需要在执行时不了解它可能处于或可能处于什么状态。 It sounds like that's your problem here, that tenBullets is being assigned by some other bit of code, at some point, and there's no definitive ordering. 听起来这是您的问题,在某些时候, tenBullets是由其他一些代码分配的,并且没有确定的顺序。

From what you have shown, I cannot say for sure, but sometimes I get inconsistencies in Eclipse, when i rename files and code snippets. 从您显示的内容来看,我不能肯定地说,但是当我重命名文件和代码片段时,有时会在Eclipse中出现不一致的情况。 Even though everything is correct, Eclipse has cached some old names, that may conflict. 即使一切正确,Eclipse仍缓存了一些旧名称,这可能会发生冲突。

To resolve this, go to project -> clean and remove all compiled files. 要解决此问题,请转到项目->清理并删除所有编译文件。

Again, not sure if this is your problem here, but I've seen it before 同样,不确定这是否是您的问题,但我之前已经看过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这段代码有时会抛出NullPointerException? - Why does this code sometimes throw a NullPointerException? JavaMail 有时会连接到 gmail,有时不会。 似乎是随机的 - JavaMail sometimes connects to gmail, sometimes not. Seems random NullPointerException,有时运行,有时抛出异常 - NullPointerException, sometimes it runs and sometimes it throws exception Java Singleton有时会引发NullPointerException - Java Singleton Sometimes Throws NullPointerException 有时会收到java.util.ConcurrentModificationException,有时则不会。 不知道为什么 - Sometimes receiving java.util.ConcurrentModificationException, sometimes not. Can't figure out why 为什么 IntelliJ 有时会抛出未使用的警告,但有时不会? - Why does IntelliJ sometimes throw an unused warning but sometimes not? `Alert` 有时会给出小得离谱的窗口 - 如何解决这个问题? - `Alert` sometimes gives ridiculously small windows - how to fix this? Android Keystore getEntry()和generateKeyPair()有时会抛出异常 - Android Keystore getEntry() and generateKeyPair() throw Exceptions sometimes 解析URL的意图有时为null,抛出NullPointerException - Resolving intent for URL is sometimes null, throws NullPointerException Android:getContext()。getContentResolver()有时会获得NullPointerException - Android: getContext().getContentResolver() sometimes gets NullPointerException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM