catch代码块中的异常类顺序是先子类后父类
try { // try语句中包含可能出现异常的程序代码
String str = "lili"; // 定义字符串变量
System.out.println(str + "年龄是:"); // 输出的信息
int age = Integer.parseInt("20l"); // 数据类型转换
System.out.println(age);
}
catch(NumberFormatException nfx) {
//nfx.printStackTrace();
}
catch (Exception e) { // catch代码块用来获取异常信息
e.printStackTrace(); // 输出异常性质
}
finally{
System.out.println("program over"); // 输出信息
}
finally代码都要执行
除了前面代码有错、前面程序退出System.exit()
throws
static void pop() throws NegativeArraySizeException {
// 定义方法并抛出NegativeArraySizeException异常
int[] arr = new int[-3]; // 创建数组
}
public static void main(String[] args) { // 主方法
try { // try语句处理异常信息
pop(); // 调用pop()方法
} catch (NegativeArraySizeException e) {
System.out.println("pop()方法抛出的异常"); // 输出异常信息
}
}
thows 用在方法声明后面,表示抛出异常,由方法的调用者处理, 而thow 用在方法体内,用来制造个(2 ) thow是声明这个方法会抛出这种类型的异常,以便使它的调用者知道要捕获这个异常,而thow是直接抛出一个异常实例。
(3)trows表示出现异常的一 种可能性,并不一 定会发生这些异常,如果使用thow,就定会产生某种异常
if (num2 == 0) // 判断num2是否等于0,如果等于0,抛出异常
{
// 抛出ArithmeticException异常
throw new ArithmeticException("这都不会,小学生都知道:除数不能是0!!!");
}
算术异常类:ArithmeticExecption
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException
数组负下标异常:NegativeArrayException
数组下标越界异常:ArrayIndexOutOfBoundsException
违背安全原则异常:SecturityException
文件已结束异常:EOFException
文件未找到异常:FileNotFoundException
字符串转换为数字异常:NumberFormatException