ClassCastException异常:
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
public class Test5{public static void main(String[] args){Animal a = new Dog();Cat c = (Cat)a;}
}
执行结果如图所示:
解决 ClassCastException 的典型方式:
public class Test5{public static void main(String[] args){Animal a = new Dog();if(a instanceof Cat){Cat a = (Cat)a;}}
}
ArraysIndexOutOfBoundsException 异常:
public class Test6{public static void main(String[] args){int[] arr = new int[5];System.out.println(arr[5]);}
}
执行结果如图所示:
解决数组索引越界异常的方式,增加关于边界的判断:
public class Test6{public static void main(String[] args){int[] arr = new int[5];int a = 5;if(a < arr.length){System.out.println(arr[a]);}}
}