在java面试中经常会询问Exception和RuntimeException的区别。
在java的异常类体系中,Error和RuntimeException是非检查型异常,其他的都是检查型异常。
请看以下一段代码:字符串变为整型
class test {
public static void main(String[] args) {
String str = "123";
int tmp = Integer.parseInt(str);
System.out.println(tmp*tmp);
}
}
从以上将字符串变为整型的代码来看,Integer因为开头首字母大小,所以肯定是一个类,而parseInt()方法可以直接由类名称调用,所以此方法肯定是一个静态方法。
此方法定义如下
public static int parseInt(String s) throws NumberFormatException;
以上方法在声明时使用了throws关键字,但是在方法调用时并没有使用try...catch进行处理,这是为什么呢?
NumberFormatException属于RuntimeException的子类,那么就可以得到下面的概念:
1、Exception在程序中必须使用try...catch进行处理;
2、RuntimeException可以不使用try...catch进行处理,但是有异常发生,则有JVM进行处理。
注意:对于RuntimeException的子类最好也使用异常处理机制。虽然RuntimeException的异常可以不用try...catch进行处理,但是如果一旦发生异常,则肯定会导致程序中断执行。所以为了保证程序在出错后依然可以执行,所以在代码开发过程中最好使用try...catch进行处理。
常见的RuntimeException
1、NullPointerException: 一般都是在null对象上调用方法了
<span style="white-space:pre"> </span>String s = null;
boolean flag = s.equals(""); //NullPointerException
这里的一看就明白了,为什么一到程序中就晕了呢?
public int getNum(String str){
if(str.equals("A"))
return 1;
else if(str.equals("B"))
return 2;
}
这个方法有可能就抛出NullPointerException。
public int getNum(String str){
if(str==null)
throw new NullPointerException("参数不能为空");
if(str.equals("A"))
return 1;
else if(str.equals("B"))
return 2;
}
2、NumberFormatException:继承IllegalArgumentException,字符串转换为数字出现。
如 int i = Integer.parseInt("abc");
3、ArrayIndexOutOfException:数组越界。如int[] a = new int[3]; int b = a[3];
4、StringIndexOutOfBoundsException:字符串越界。如String s = "hello"; char a = s.charAt(6);
5、ClassCastException:类型转换错误。如Object obj = new Object(); String s = (String) obj;
6、UnsupportedOperationException:该操作不被支持。
7、ArithmeticException:算术错误,典型的就是除0.
8、IllegalArgumentException:非法参数