请你说出Java中几种常见的RuntimeException?这是面试过程中经常被问到的问题,业余时间做了简单总结,希望能对大家有所帮助,如有不足希望指出。
1. NullPointerException (空指针引用异常)
String str = null; str.toString();
Exception in thread "main" java.lang.NullPointerException
2.ClassCastException(类型强制转换异常)
Object str = "abc"; Integer integer =(Integer)str;
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
3. IllegalArgumentException(传递非法参数异常)
System.out.println(Timestamp.valueOf("2019/02/15 00:00:00"));
Exception in thread "main" java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
4.ArithmeticException ( 算术运算异常)
System.out.println(2/0);
Exception in thread "main" java.lang.ArithmeticException: / by zero
5. ArrayIndexOutOfBoundsException (数组下标越界异常)
String[] strings = {"a"};
System.out.println(strings[1]);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
6. NegativeArraySizeException(数组负下标异常)
String[] strings = new String[-1];
Exception in thread "main" java.lang.NegativeArraySizeException
7. NumberFormatException(数字格式异常)
Integer integer = Integer.parseInt("o");
Exception in thread "main" java.lang.NumberFormatException: For input string: "o"
8. ArrayStoreException(数组存储异常)
Object[] strings = new String[2]; strings[0]=0;
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
9. IndexOutOfBoundsException (下标越界异常)
List list = new ArrayList(); list.get(0);
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
这里就先简单介绍这几种,想详细了解的同学可以自行翻看源码。