一、运行时异常(RuntimeException)
1、NullPointerException(空指针异常)
package com.geminno.homework0222;
public class ExceptionExample01 {
// 空指针异常事例
public static void main(String[] args) {
// TODO Auto-generated method stub
String i=null;
System.out.println(i.toString());
}
}
结果:
2、ArrayIndexOutOfBoundsException(数组下标越界异常)
package com.geminno.homework0222;
public class IndexOutOfBoundsException02 {
public static void main(String[] args) {
String []arrays=new String[5];
for (int i = 0; i <= arrays.length; i++) {
arrays[i]=i+1+" ";
}
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
}
}
结果:
3、ClassCastException(类型转换异常)
package com.geminno.homework0222;
public class ClassCastException03 {
public static void main(String[] args) {
Object i="hahaha";
System.out.println((Integer)i);
}
}
结果:
4、ArithmeticException(数学异常)
package com.geminno.homework0222;
public class ArithmeticException04 {
public static void main(String[] args) {
int i=5/0;
System.out.println(i);
}
}
结果:
5、ArrayStoreException(存储数组类型异常)
package com.geminno.homework0222;
public class ArrayStoreException05 {
public static void main(String[] args) {
Object []arrays=new String[3];
arrays[0]="警察";
arrays[1]=new Integer(564);
arrays[2]=new Double(4512);
}
}
结果:
5、NegativeArraySizeException(数组长度为负数异常)
package com.geminno.homework0222;
public class IndexOutOfBoundsException02 {
public static void main(String[] args) {
String []arrays=new String[-1];
for (int i = 0; i <= arrays.length; i++) {
arrays[i]=i+1+" ";
}
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
}
}
结果:
一、检查时异常
说明:此类异常在JVM上都不会编译通过,即在javac是就不会通过,如果不对其进行处理,程序就不会编译通过
常见的受检查时异常有:1、ClassNotFoundException