![](/img/trans.png)
[英]Why does any try/catch past while loop cause Null Pointer Exception
[英]Why does this cause a null pointer exception?
我有以下代碼:
public class Sprite {
protected float x;
protected float y;
protected Image image;
protected Rectangle boundingBox;
Sprite(float x, float y, Image image) {
this.x = x;
this.y = y;
this.image = image;
boundingBox = new Rectangle(x, y,
this.image.getWidth(), this.image.getHeight());
}
...
public Rectangle getBoundingBox() {
return boundingBox;
}
但是,當我已經定義並初始化了精靈對象時,在另一個類中調用此函數時:
public static boolean collides(Sprite object1, Sprite object2) {
return object1.getBoundingBox().intersects(object2.getBoundingBox());
}
我得到一個空指針異常,指向包含以下內容的行:
this.image.getWidth(), this.image.getHeight());
為什么是這樣?
檢查圖像是否為空。 這最有可能是錯誤的來源。
在某個地方創建Sprite
並向構造函數傳遞一個空圖像。 在您的構造函數中嘗試做這樣的事情
if (image == null) throw new Exception("Cannot create Sprite with null image")
如果image
為null
,就會發生這種情況。 您必須在代碼中的某個位置進行此調用:
new Sprite(aFloat, anotherFloat, aNullValue); // aNullValue == null
您可能想要在構造函數中添加一些引發RuntimeException
null
檢查。 這將使查找null
Image
傳遞的代碼變得容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.