黑马程序员技术交流社区

标题: RuntimeException异常 [打印本页]

作者: 王丽    时间: 2011-7-27 06:19
标题: RuntimeException异常
常见的RuntimeException异常有哪些?怎样解决啊?
作者: 匿名    时间: 2011-7-27 08:19
以下内容为搜索得来:
RuntimeException:RuntimeException继承了Exception,而不是直接继Error, 这个表示系统异常,比较严重。
RuntimeException可以说见的最多了,下面我们说明一下常见的RuntimeException:



NullPointerException:见的最多了,其实很简单,一般都是在null对象上调用方法了。
String s=null;
boolean eq=s.equals(""); // NullPointerException
这里你看的非常明白了,为什么一到程序中就晕呢?
public int getNumber(String str){
  if(str.equals("A")) return 1;
   else if(str.equals("B")) return 2;
}
这个方法就有可能抛出NullPointerException,我建议你主动抛出异常,因为代码一多,你可能又晕了。
public int getNumber(String str){
  if(str==null) throw new NullPointerException("参数不能为空");
                                    //你是否觉得明白多了
  if(str.equals("A")) return 1;
   else if(str.equals("B")) return 2;
}



NumberFormatException:继承IllegalArgumentException,字符串转换为数字时。
比如int i= Integer.parseInt("ab3");



ArrayIndexOutOfBoundsException:数组越界
比如 int[] a=new int[3]; int b=a[3];



StringIndexOutOfBoundsException:字符串越界
比如 String s="hello"; char c=s.chatAt(6);



ClassCastException:类型转换错误
比如 Object obj=new Object(); String s=(String)obj;



UnsupportedOperationException:该***作不被支持,如果我们希望不支持这个方法,可以抛出这个异常。既然不支持还要这个干吗?有可能子类中不想支持父类中有的方法,可以直接抛出这个异常。



ArithmeticException:算术错误,典型的就是0作为除数的时候。



IllegalArgumentException:非法参数,在把字符串转换成数字的时候经常出现的一个异常,我们可以在自己的程序中好好利用这个异常。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2