Java中的运行时异常是RuntimeException。Java面试中可能问平时遇到哪些异常,以下列出Java中一些常见的运行时异常和举例说明。

ArithmeticException:算术运算异常。

例子

最常见的算术运算异常是1/0

System.out.println(1 / 0);
输出
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at HelloWorld.main(HelloWorld.java:6)

NullPointerException: 空指针引用异常

例子
String str = null;
System.out.println(str.length());
输出
Exception in thread "main" java.lang.NullPointerException
    at HelloWorld.main(HelloWorld.java:7)

上面的例子中我们定义了一个字符串为null,调用它的方法便会报错空指针异常NullPointerException 。 

ClassCastException: 类型强制转换异常

例子

Object object = new Integer(0);
String str = (String)object;
System.out.println(str);
输出
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at HelloWorld.main(HelloWorld.java:6)

IndexOutOfBoundsException:下标越界异常

例子

List<String> list = new ArrayList();
list.add("1");
System.out.println(list.get(1));

输出

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:659)
    at java.util.ArrayList.get(ArrayList.java:435)
    at HelloWorld.main(HelloWorld.java:9)

 

上面的例子中我们定义一个列表list并往其中添加了一个元素,且最大的下表为0,但是我们访问了下标为1的元素,则提示下标越界异常。

NumberFormatException:数字格式异常

例子

String str = "123y";
System.out.println(Integer.parseInt(str));

输出

Exception in thread "main" java.lang.NumberFormatException: For input string: "123y"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at HelloWorld.main(HelloWorld.java:8)

 我们把"123y"转为Integer提示异常NumberFormatException 。