Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12707
  • 博文数量: 12
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 110
  • 用 户 组: 普通用户
  • 注册时间: 2015-09-01 16:24
个人简介

简简单单学习,快快乐乐生活。。。。

文章存档

2017年(1)

2016年(4)

2015年(8)

分类: Java

2016-08-26 21:34:51

一:java.lang.NullPointerException

java中一个常见的异常类,空指针异常。

 当你的程序在调用对象,或者使用对象的时候,使用了null时,会抛出这种异常。

    包括以下几种情况:

1.    访问或修改 null 对象的字段。

2.    调用 null 对象的实例方法。

3.    如果一个数组为null,试图用属性length获得其长度时

4.    如果一个数组为null,试图访问或修改其中某个元素时。

5.    在需要抛出一个异常对象,而该对象为 null 时。

  当你的程序运行时,抛出了这个异常,说明程序中有对null的非法使用。

   下面是以上5种情况的实例(参考)

   1)调用 null 对象的实例方法。










10




 

 

class Point {

    public int x, y;

    public int getX() { 

        return x;

    }

}

 

public class TestNullPointerException {

    static Point p1;

    public static void main(String args[]){

    p1.getX(); // 此处抛出NullPointerException    

   }

}

2)访问或修改 null 对象的字段。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

 

class Point {

    public int x, y;

    public int getX() { 

        return x;

    }

}

 public class TestNullPointerException {

    static Point p1;

    public static void main(String args[]){

    p1.x = 1; // 此处抛出NullPointerException     

    }

}

3)如果一个数组为null,试图用属性length获得其长度时。

 

1

2

3

4

5

6

public class TestNullPointerException {

    static int[] ia;

    public static void main(String args[]){        

   System.out.println(ia.length);// 此处抛出NullPointerException

    }

}

4)如果一个数组为null,试图访问或修改其中某个元素时。

1

2

3

4

5

6

7

8

public class TestNullPointerException {

    static int[] ia;

    public static void main(String args[]){        

     ia[0] = 1;    // 此处抛出NullPointerException        

    }

}

5)在需要抛出一个异常对象,而该对象为 null 时。

1

2

3

4

5

6

7

8

9

class MyException extends RuntimeException {

}

 public class TestNullPointerException {

  static MyException e;

     

    public static void main(String args[]){                

    throw e; // 此处抛出NullPointerException

    }

}

阅读(309) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~