常见的运行时异常(目录)
NullPointerException空指针异常ArithmeticException数字运算异常ArrayIndexOutOfBoundsException数组下标越界异常ClassCastException类型装换异常NumberFormatException数字格式不正确异常[]NullPointerException空指针异常 [NullPointerException_.java]
当应用程序视图在需要对象的地方使用null时,抛出该异常,案例演示:
package com.tao.exception_;/*** Create By 刘鸿涛* /12/31 14:32*/public class NullPointerException {public static void main(String[] args) {String name = null;System.out.println(name.length());}}
ArithmeticException数字运算异常 [ArithmeticException_]
当出现异常的运算条件时,抛出此异常。例如,一个整数“除以零”时,抛出此类的一个实例
package com.tao.exception_;/*** Create By 刘鸿涛* /12/31 15:03*/public class ArithmeticException_ {public static void main(String[] args) {int n1 = 4;int n2 = 0;System.out.println(n1 / n2);}}
ArayIndexOutOfBoundsException数组下标越界异常 [ArrayIndexOutOfBoundsException_.java]
用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引
package com.tao.exception_;/*** Create By 刘鸿涛* /12/31 14:36*/public class ArrayIndexOutOfBoundsException_ {public static void main(String[] args) {int[] arr = {1,2,4};for(int i = 0; i <= arr.length; i++){System.out.println(arr[i]);}}}
ClassCastException类型转换异常 [ClassCastException_.java]
当试图将对象强制转换为不是实例的子类时,抛出该异常。例如,以下代码将生成一个ClassCastException
package com.tao.exception_;/*** Create By 刘鸿涛* /12/31 14:40*/public class ClassCastException_ {public static void main(String[] args) {A b = new B(); //向上转型B b2 = (B)b; //向下转型,这里是OKC c2 = (C)b; //这里抛出ClassCastException}}class A{}class B extends A{}class C extends A{}
NumberFormatException数字格式不正确异常 [NumberFormatException_.java]
当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常 = > 使用异常我们可以确保输入是否满足条件数字。
package com.tao.exception_;/*** Create By 刘鸿涛* /12/31 14:53*/public class NumberFormatException_ {public static void main(String[] args) {// String name = "1234";// 将String 转换成 int// int num = Integer.parseInt(name);// System.out.println(num); //1234String name = "taotao";// 将String 转换成 intint num = Integer.parseInt(name);System.out.println(num); //异常,无法转型}}