JAVA异常体系图
在整个体系中以继承的关系来说“根类是Throwable”Erray错误是不可以被修复的,Excepion异常是可以修复的;Excepion又分为运行时异常和非运行时异常。以下是运行时异常的实例:
算数异常:
public class Excpion {
public static void main(String[] args) {
//算数异常
int a = 10;
int b = 0;
int[] c = {};
c[0] = 3;
System.out.println(a/b);
System.out.println(c[0] = 3);
}
}
算数异常
Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.excpion.test.Excpion.main(Excpion.java:7)
类型异常:这里用到“多态” 的向下造型
public class Excpion {
public static void main(String[] args) {
//类型
Animal a1 = new Dog();
Animal a2 = new Cat();
Dog d1 = (Dog)a1;
Dog d2 = (Dog)a2; //强转
}
}
class Animal{
}
public class Cat extends Animal {
String Cat;
}
public class Dog extends Animal {
String Dog;
}
类型转换异常
Exception in thread “main” java.lang.ClassCastException: com.excpion.test.Cat cannot be cast to com.excpion.test.Dog
at com.excpion.test.Excpion.main(Excpion.java:26)
空指针异常:
public class Excpion {
public static void main(String[] args) {
//空指针
int a = 10;
int b = 0;
Excpion t1 = new Excpion();
Excpion t2 = null;
System.out.println(t1.a);
System.out.println(t2.a);
System.out.println(t2.c());
}
private String c() {
return "123";
}
}
空指针
Exception in thread “main” java.lang.NullPointerException
at com.excpion.test.Excpion.main(Excpion.java:16)
数组越界:
public class Excpion {
public static void main(String[] args) {
//数组越界
int[] c = {};
c[0] = 3;
System.out.println(a/b);
System.out.println(c[0] = 3);
try {
System.out.println(a/b);
}catch(ArithmeticException e) {
System.out.println("数组越界异常");
}
}
}
引索越界
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
at com.excpion.test.Excpion.main(Excpion.java:11)